This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 0f54dc7fddc2 CAMEL-27385: camel-core - Scheduled poll consumer: a poll
that runs over a stop and start does not change the restarted consumer (#30703)
0f54dc7fddc2 is described below
commit 0f54dc7fddc2b597cf8de609564152f979a0791e
Author: allthingssecurity <[email protected]>
AuthorDate: Tue Nov 24 12:14:14 2026 +0530
CAMEL-27385: camel-core - Scheduled poll consumer: a poll that runs over a
stop and start does not change the restarted consumer (#30703)
A poll that is still running when the consumer is stopped could change the
restarted consumer: forceConsumerAsReady() made it ready before it polled, a
run with a used up repeatCount cancelled its scheduled task, and the error
state, firstPollDone and the backoff counters of the old poll could be kept.
doStop now increments the generation and clears the state under a lock, and
a
poll checks its generation and writes the state under the same lock
(backoff,
repeat count and unscheduleTask, greedy, onPolled and the final writes).
forceConsumerAsReady() called from a poll is ignored when the consumer was
stopped since that poll started. The lock is not held while polling.
Found with a TLA+ model.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../impl/ScheduledPollConsumerStaleRunTest.java | 340 +++++++++++++++++++++
.../camel/support/ScheduledPollConsumer.java | 255 ++++++++++------
2 files changed, 497 insertions(+), 98 deletions(-)
diff --git
a/core/camel-core/src/test/java/org/apache/camel/impl/ScheduledPollConsumerStaleRunTest.java
b/core/camel-core/src/test/java/org/apache/camel/impl/ScheduledPollConsumerStaleRunTest.java
new file mode 100644
index 000000000000..abbf9b66cc7a
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/impl/ScheduledPollConsumerStaleRunTest.java
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.impl;
+
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Endpoint;
+import org.apache.camel.spi.HttpResponseAware;
+import org.apache.camel.support.DefaultScheduledPollConsumerScheduler;
+import org.apache.camel.support.ScheduledPollConsumer;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A poll that is still running when the consumer is stopped and started again
must not change the state of the
+ * restarted consumer.
+ */
+class ScheduledPollConsumerStaleRunTest extends ContextTestSupport {
+
+ private final CountDownLatch release = new CountDownLatch(1);
+ private Thread poller;
+ private Thread restarter;
+ private StaleConsumer consumer;
+
+ private static void awaitRelease(CountDownLatch latch) {
+ try {
+ if (!latch.await(20, TimeUnit.SECONDS)) {
+ throw new IllegalStateException("Not released");
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ }
+
+ private static class StaleConsumer extends ScheduledPollConsumer {
+
+ private volatile boolean forceReadyInPoll;
+ private volatile Exception exceptionToThrowOnPoll;
+ // set to hold the next poll (the remote call of the poll is in
progress)
+ private volatile CountDownLatch pollHeld;
+ // set to hold the next call of addLastErrorDetail (after the
generation check of the poll)
+ private volatile CountDownLatch detailHeld;
+ // set to hold the next isSuspended() check of a run on the stale-poll
thread (when the run has started)
+ private volatile CountDownLatch runStartHeld;
+ private volatile CountDownLatch release;
+
+ StaleConsumer(Endpoint endpoint) {
+ super(endpoint, null);
+ }
+
+ @Override
+ protected int poll() throws Exception {
+ CountDownLatch held = pollHeld;
+ if (held != null) {
+ pollHeld = null;
+ held.countDown();
+ awaitRelease(release);
+ }
+ if (forceReadyInPoll) {
+ // such as camel-aws2-sqs when its receive call returns
+ forceConsumerAsReady();
+ }
+ Exception e = exceptionToThrowOnPoll;
+ if (e != null) {
+ throw e;
+ }
+ return 0;
+ }
+
+ @Override
+ protected void addLastErrorDetail(String key, Object value) {
+ CountDownLatch held = detailHeld;
+ if (held != null) {
+ detailHeld = null;
+ held.countDown();
+ awaitRelease(release);
+ }
+ super.addLastErrorDetail(key, value);
+ }
+
+ @Override
+ public boolean isSuspended() {
+ CountDownLatch held = runStartHeld;
+ if (held != null &&
"stale-poll".equals(Thread.currentThread().getName())) {
+ runStartHeld = null;
+ held.countDown();
+ awaitRelease(release);
+ }
+ return super.isSuspended();
+ }
+
+ Map<String, Object> lastErrorDetails() {
+ return getLastErrorDetails();
+ }
+ }
+
+ // a scheduler that holds its next unscheduleTask() call before it cancels
the tasks
+ private static class HoldingScheduler extends
DefaultScheduledPollConsumerScheduler {
+
+ private volatile CountDownLatch unscheduleHeld;
+ private volatile CountDownLatch release;
+
+ @Override
+ public void unscheduleTask() {
+ CountDownLatch held = unscheduleHeld;
+ if (held != null) {
+ unscheduleHeld = null;
+ held.countDown();
+ awaitRelease(release);
+ }
+ super.unscheduleTask();
+ }
+ }
+
+ private static class MyHttpException extends Exception implements
HttpResponseAware {
+ MyHttpException() {
+ super("Service unavailable");
+ }
+
+ @Override
+ public int getHttpResponseCode() {
+ return 503;
+ }
+
+ @Override
+ public void setHttpResponseCode(int code) {
+ // noop
+ }
+
+ @Override
+ public String getHttpResponseStatus() {
+ return "Service Unavailable";
+ }
+
+ @Override
+ public void setHttpResponseStatus(String status) {
+ // noop
+ }
+ }
+
+ @AfterEach
+ void cleanUp() throws Exception {
+ release.countDown();
+ if (poller != null) {
+ poller.join(10000);
+ assertFalse(poller.isAlive(), "the poll did not complete");
+ }
+ if (restarter != null) {
+ restarter.join(10000);
+ assertFalse(restarter.isAlive(), "the restart did not complete");
+ }
+ if (consumer != null) {
+ consumer.stop();
+ }
+ }
+
+ private StaleConsumer newConsumer() {
+ consumer = new StaleConsumer(getMockEndpoint("mock:foo"));
+ consumer.release = release;
+ // the polls are run by the test
+ consumer.setStartScheduler(false);
+ return consumer;
+ }
+
+ private void startPoller() {
+ poller = new Thread(consumer::run, "stale-poll");
+ poller.start();
+ }
+
+ private void joinPoller() throws InterruptedException {
+ poller.join(10000);
+ assertFalse(poller.isAlive(), "the poll did not complete");
+ }
+
+ /**
+ * Stops and starts the consumer in another thread, and returns once that
thread is done or waits for the poll in
+ * progress (with the fix, the stop waits until the poll has updated the
state of before the stop).
+ */
+ private void restartWhilePollIsHeld() {
+ CountDownLatch restarted = new CountDownLatch(1);
+ restarter = new Thread(() -> {
+ consumer.stop();
+ consumer.start();
+ restarted.countDown();
+ }, "restart");
+ restarter.start();
+ await().atMost(10, TimeUnit.SECONDS)
+ .until(() -> restarted.getCount() == 0 || restarter.getState()
== Thread.State.WAITING);
+ }
+
+ @Test
+ void forceReadyOfPollFromBeforeStopIsIgnored() throws Exception {
+ newConsumer();
+ consumer.forceReadyInPoll = true;
+ CountDownLatch pollHeld = new CountDownLatch(1);
+ consumer.pollHeld = pollHeld;
+ consumer.start();
+
+ startPoller();
+ assertTrue(pollHeld.await(10, TimeUnit.SECONDS));
+
+ // stop and start while the remote call of the poll is in progress
(such as a long poll)
+ consumer.stop();
+ consumer.start();
+ assertFalse(consumer.isConsumerReady());
+
+ // the remote call returns, and the poll forces the consumer as ready
+ release.countDown();
+ joinPoller();
+ assertFalse(consumer.isConsumerReady(), "the restarted consumer has
not polled yet");
+
+ // a poll of the restarted consumer forces it as ready
+ consumer.run();
+ assertTrue(consumer.isConsumerReady());
+ }
+
+ @Test
+ void stateOfPollFromBeforeStopIsNotKept() throws Exception {
+ newConsumer();
+ consumer.exceptionToThrowOnPoll = new MyHttpException();
+ CountDownLatch detailHeld = new CountDownLatch(1);
+ consumer.detailHeld = detailHeld;
+ consumer.start();
+
+ // the poll fails, and is held after it has checked that the consumer
was not stopped
+ startPoller();
+ assertTrue(detailHeld.await(10, TimeUnit.SECONDS));
+
+ restartWhilePollIsHeld();
+ release.countDown();
+ joinPoller();
+ restarter.join(10000);
+ assertFalse(restarter.isAlive(), "the restart did not complete");
+
+ assertTrue(consumer.isStarted());
+ assertFalse(consumer.isFirstPollDone(), "the restarted consumer has
not polled yet");
+ assertEquals(0, consumer.getErrorCounter());
+ assertNull(consumer.lastErrorDetails());
+ }
+
+ @Test
+ void repeatCountOfRunFromBeforeStopDoesNotUnscheduleRestartedConsumer()
throws Exception {
+ newConsumer();
+ HoldingScheduler scheduler = new HoldingScheduler();
+ scheduler.release = release;
+ // the scheduled tasks do not run during the test
+ scheduler.setInitialDelay(TimeUnit.HOURS.toMillis(1));
+ consumer.setScheduler(scheduler);
+ consumer.setStartScheduler(true);
+ consumer.setRepeatCount(1);
+ consumer.start();
+
+ // the first run polls
+ consumer.run();
+ assertEquals(1, consumer.getCounter());
+ assertTrue(scheduler.isSchedulerStarted());
+
+ // the second run has used up the repeat count, and is held before it
unschedules the task
+ CountDownLatch unscheduleHeld = new CountDownLatch(1);
+ scheduler.unscheduleHeld = unscheduleHeld;
+ startPoller();
+ assertTrue(unscheduleHeld.await(10, TimeUnit.SECONDS));
+
+ restartWhilePollIsHeld();
+ release.countDown();
+ joinPoller();
+ restarter.join(10000);
+ assertFalse(restarter.isAlive(), "the restart did not complete");
+
+ assertTrue(consumer.isStarted());
+ assertTrue(scheduler.isSchedulerStarted(), "the restarted consumer
lost its scheduled task");
+ assertEquals(0, consumer.getCounter());
+ }
+
+ @Test
+ void backoffOfPollFromBeforeStopIsNotKept() throws Exception {
+ newConsumer();
+ consumer.setBackoffMultiplier(2);
+ consumer.setBackoffErrorThreshold(1);
+ consumer.exceptionToThrowOnPoll = new MyHttpException();
+ consumer.start();
+
+ // the consumer is failing
+ consumer.run();
+ assertEquals(1, consumer.getErrorCounter());
+
+ // the next run has started, and is held before its backoff check
+ CountDownLatch runStartHeld = new CountDownLatch(1);
+ consumer.runStartHeld = runStartHeld;
+ startPoller();
+ assertTrue(runStartHeld.await(10, TimeUnit.SECONDS));
+
+ consumer.stop();
+ consumer.start();
+ assertEquals(0, consumer.getErrorCounter());
+
+ // the first poll of the restarted consumer fails too
+ consumer.run();
+ assertEquals(1, consumer.getCounter());
+ assertEquals(1, consumer.getErrorCounter());
+ assertEquals(0, consumer.getBackoffCounter());
+
+ // the run from before the stop goes on
+ release.countDown();
+ joinPoller();
+ assertEquals(0, consumer.getBackoffCounter(), "the run from before the
stop changed the backoff counter");
+ assertEquals(1, consumer.getCounter());
+ assertEquals(1, consumer.getErrorCounter());
+
+ // the next run of the restarted consumer backs off after its first
error, as configured (the error base of
+ // the backoff is still 0)
+ consumer.run();
+ assertEquals(1, consumer.getBackoffCounter());
+ assertEquals(1, consumer.getCounter(), "the restarted consumer polled
instead of backing off");
+ }
+}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/ScheduledPollConsumer.java
b/core/camel-support/src/main/java/org/apache/camel/support/ScheduledPollConsumer.java
index 9b61b556bd14..2d4ea9d897e1 100644
---
a/core/camel-support/src/main/java/org/apache/camel/support/ScheduledPollConsumer.java
+++
b/core/camel-support/src/main/java/org/apache/camel/support/ScheduledPollConsumer.java
@@ -23,6 +23,8 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
import org.apache.camel.Component;
import org.apache.camel.Endpoint;
@@ -87,6 +89,12 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
private final AtomicLong backoffErrorBase = new AtomicLong();
// incremented when the consumer is stopped, so a poll that is still
running does not update the state afterwards
private final AtomicLong generation = new AtomicLong();
+ // held by doStop to increment the generation and clear the state, and by
a poll to check the generation and
+ // update the state: a stop (and start) can then not happen between the
check and the update
+ private final Lock stateLock = new ReentrantLock();
+ // the generation of the poll in progress on this thread, so
forceConsumerAsReady() of a poll of before a stop
+ // is ignored
+ private final ThreadLocal<Long> pollGeneration = new ThreadLocal<>();
// whether this consumer created the scheduler (and therefore configures
it)
private boolean consumerCreatedScheduler;
private volatile boolean forceReady;
@@ -163,40 +171,53 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
return;
}
- // should we backoff if its enabled, and either the idle or error
counter is > the threshold
- if (backoffMultiplier > 0
- // either idle or error threshold could be not in use, so
check for that and use MAX_VALUE if not in use
- && (idleCounter.longValue() >= (backoffIdleThreshold > 0 ?
backoffIdleThreshold : Integer.MAX_VALUE)
- || errorCounter.longValue() -
backoffErrorBase.longValue() >= (backoffErrorThreshold > 0
- ? backoffErrorThreshold : Integer.MAX_VALUE)))
{
- final int currentBackoffCounter = backoffCounter.incrementAndGet();
- if (currentBackoffCounter < backoffMultiplier) {
- // yes we should backoff
- if (idleCounter.intValue() > 0) {
- LOG.debug("doRun() backoff due subsequent {} idles
(backoff at {}/{})", idleCounter.longValue(),
- backoffCounter.intValue(), backoffMultiplier);
+ stateLock.lock();
+ try {
+ if (currentGeneration != generation.get()) {
+ // the consumer has been stopped since this run started, so it
must not use the state of a later start
+ LOG.trace("doRun() not polling as the consumer was stopped");
+ return;
+ }
+
+ // should we backoff if its enabled, and either the idle or error
counter is > the threshold
+ if (backoffMultiplier > 0
+ // either idle or error threshold could be not in use, so
check for that and use MAX_VALUE if not in use
+ && (idleCounter.longValue() >= (backoffIdleThreshold > 0 ?
backoffIdleThreshold : Integer.MAX_VALUE)
+ || errorCounter.longValue() -
backoffErrorBase.longValue() >= (backoffErrorThreshold > 0
+ ? backoffErrorThreshold :
Integer.MAX_VALUE))) {
+ final int currentBackoffCounter =
backoffCounter.incrementAndGet();
+ if (currentBackoffCounter < backoffMultiplier) {
+ // yes we should backoff
+ if (idleCounter.intValue() > 0) {
+ LOG.debug("doRun() backoff due subsequent {} idles
(backoff at {}/{})", idleCounter.longValue(),
+ backoffCounter.intValue(), backoffMultiplier);
+ } else {
+ LOG.debug("doRun() backoff due subsequent {} errors
(backoff at {}/{})", errorCounter.intValue(),
+ backoffCounter.intValue(), backoffMultiplier);
+ }
+ return;
} else {
- LOG.debug("doRun() backoff due subsequent {} errors
(backoff at {}/{})", errorCounter.intValue(),
- backoffCounter.intValue(), backoffMultiplier);
+ // we are finished with backoff so reset counters, but
keep the error counter (the consumer is still
+ // failing until the next poll succeeds) and count the
error threshold from now on
+ idleCounter.set(0);
+ backoffErrorBase.set(errorCounter.longValue());
+ backoffCounter.set(0);
+ successCounter.set(0);
+ LOG.trace("doRun() backoff finished, resetting counters.");
}
- return;
- } else {
- // we are finished with backoff so reset counters, but keep
the error counter (the consumer is still
- // failing until the next poll succeeds) and count the error
threshold from now on
- idleCounter.set(0);
- backoffErrorBase.set(errorCounter.longValue());
- backoffCounter.set(0);
- successCounter.set(0);
- LOG.trace("doRun() backoff finished, resetting counters.");
}
- }
- long count = counter.incrementAndGet();
- boolean stopFire = repeatCount > 0 && count > repeatCount;
- if (stopFire) {
- LOG.debug("Cancelling {} scheduler as repeat count limit reached
after {} counts.", getEndpoint(), repeatCount);
- scheduler.unscheduleTask();
- return;
+ long count = counter.incrementAndGet();
+ boolean stopFire = repeatCount > 0 && count > repeatCount;
+ if (stopFire) {
+ LOG.debug("Cancelling {} scheduler as repeat count limit
reached after {} counts.", getEndpoint(),
+ repeatCount);
+ // under the lock, so the futures of a later start of the
consumer are not cancelled
+ scheduler.unscheduleTask();
+ return;
+ }
+ } finally {
+ stateLock.unlock();
}
int retryCounter = -1;
@@ -225,9 +246,11 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
if (begin) {
retryCounter++;
int polled = 0;
+ pollGeneration.set(currentGeneration);
try {
polled = poll();
} finally {
+ pollGeneration.remove();
// also a poll that failed, so a consumer that
keeps failing is seen polling
onPolled(currentGeneration, polled);
}
@@ -246,16 +269,21 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
retryCounter = -1;
LOG.trace("Greedy polling after processing {}
messages", polledMessages);
- if (currentGeneration == generation.get()) {
- // clear any error that might be since we
have successfully polled, otherwise readiness checks might believe the
- // consumer to be unhealthy
- errorCounter.set(0);
- backoffErrorBase.set(0);
- lastError = null;
- lastErrorDetails = null;
-
- // setting firstPollDone to true if greedy
polling is enabled
- firstPollDone = true;
+ stateLock.lock();
+ try {
+ if (currentGeneration == generation.get())
{
+ // clear any error that might be since
we have successfully polled, otherwise readiness checks might believe the
+ // consumer to be unhealthy
+ errorCounter.set(0);
+ backoffErrorBase.set(0);
+ lastError = null;
+ lastErrorDetails = null;
+
+ // setting firstPollDone to true if
greedy polling is enabled
+ firstPollDone = true;
+ }
+ } finally {
+ stateLock.unlock();
}
}
} else {
@@ -296,41 +324,46 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
}
}
- if (currentGeneration != generation.get()) {
- // the consumer has been stopped while polling, so the state
(which has been reset) must not be updated
- LOG.trace("doRun() done after the consumer was stopped");
- return;
- }
+ stateLock.lock();
+ try {
+ if (currentGeneration != generation.get()) {
+ // the consumer has been stopped while polling, so the state
(which has been reset) must not be updated
+ LOG.trace("doRun() done after the consumer was stopped");
+ return;
+ }
- if (cause != null) {
- idleCounter.set(0);
- successCounter.set(0);
- errorCounter.incrementAndGet();
- lastError = cause;
- // the details are for this error only
- lastErrorDetails = null;
- // enrich last error with http response code if possible
- if (cause instanceof HttpResponseAware httpResponseAware) {
- int code = httpResponseAware.getHttpResponseCode();
- if (code > 0) {
- addLastErrorDetail(HealthCheck.HTTP_RESPONSE_CODE, code);
+ if (cause != null) {
+ idleCounter.set(0);
+ successCounter.set(0);
+ errorCounter.incrementAndGet();
+ lastError = cause;
+ // the details are for this error only
+ lastErrorDetails = null;
+ // enrich last error with http response code if possible
+ if (cause instanceof HttpResponseAware httpResponseAware) {
+ int code = httpResponseAware.getHttpResponseCode();
+ if (code > 0) {
+ addLastErrorDetail(HealthCheck.HTTP_RESPONSE_CODE,
code);
+ }
}
- }
- } else {
- if (polledMessages == 0) {
- idleCounter.incrementAndGet();
} else {
- idleCounter.set(0);
+ if (polledMessages == 0) {
+ idleCounter.incrementAndGet();
+ } else {
+ idleCounter.set(0);
+ }
+ successCounter.incrementAndGet();
+ errorCounter.set(0);
+ backoffErrorBase.set(0);
+ lastError = null;
+ lastErrorDetails = null;
}
- successCounter.incrementAndGet();
- errorCounter.set(0);
- backoffErrorBase.set(0);
- lastError = null;
- lastErrorDetails = null;
- }
- // now first pool is done after the poll is complete
- firstPollDone = true;
+ // now first pool is done after the poll is complete
+ firstPollDone = true;
+ } finally {
+ stateLock.unlock();
+ }
LOG.trace("doRun() done with idleCounter={}, successCounter={},
errorCounter={}", idleCounter.longValue(),
successCounter.longValue(), errorCounter.longValue());
@@ -344,16 +377,21 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
* the developer consoles show (not {@code TimeSource}, which is for waits
and durations).
*/
private void onPolled(long currentGeneration, int polledMessages) {
- if (currentGeneration != generation.get()) {
- // the consumer has been stopped while polling, so the state
(which has been reset) must not be updated
- return;
- }
- long now = System.currentTimeMillis();
- if (polledMessages > 0) {
- lastPollMessagesCount = polledMessages;
- lastPollMessagesTimestamp = now;
+ stateLock.lock();
+ try {
+ if (currentGeneration != generation.get()) {
+ // the consumer has been stopped while polling, so the state
(which has been reset) must not be updated
+ return;
+ }
+ long now = System.currentTimeMillis();
+ if (polledMessages > 0) {
+ lastPollMessagesCount = polledMessages;
+ lastPollMessagesTimestamp = now;
+ }
+ lastPollTimestamp = now;
+ } finally {
+ stateLock.unlock();
}
- lastPollTimestamp = now;
}
/**
@@ -645,9 +683,25 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
*
* This is for example needed by the FTP component as polling a large file
can take long time, causing a
* health-check to not be ready within reasonable time.
+ *
+ * When called from a poll that started before the consumer was stopped
(such as a long poll that returns after the
+ * consumer has been restarted), this does nothing: the poll is not a poll
of the restarted consumer.
*/
protected void forceConsumerAsReady() {
- forceReady = true;
+ Long pollGen = pollGeneration.get();
+ if (pollGen == null) {
+ // not called from a poll of this consumer
+ forceReady = true;
+ return;
+ }
+ stateLock.lock();
+ try {
+ if (pollGen == generation.get()) {
+ forceReady = true;
+ }
+ } finally {
+ stateLock.unlock();
+ }
}
/**
@@ -842,24 +896,29 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
ServiceHelper.stopAndShutdownServices(scheduler);
}
- // a poll that is still running must not update the state after it has
been cleared
- generation.incrementAndGet();
-
- // clear counters
- backoffCounter.set(0);
- idleCounter.set(0);
- errorCounter.set(0);
- backoffErrorBase.set(0);
- successCounter.set(0);
- counter.set(0);
- lastPollTimestamp = 0;
- lastPollMessagesTimestamp = 0;
- lastPollMessagesCount = 0;
- // clear ready state
- firstPollDone = false;
- forceReady = false;
- lastError = null;
- lastErrorDetails = null;
+ stateLock.lock();
+ try {
+ // a poll that is still running must not update the state after it
has been cleared
+ generation.incrementAndGet();
+
+ // clear counters
+ backoffCounter.set(0);
+ idleCounter.set(0);
+ errorCounter.set(0);
+ backoffErrorBase.set(0);
+ successCounter.set(0);
+ counter.set(0);
+ lastPollTimestamp = 0;
+ lastPollMessagesTimestamp = 0;
+ lastPollMessagesCount = 0;
+ // clear ready state
+ firstPollDone = false;
+ forceReady = false;
+ lastError = null;
+ lastErrorDetails = null;
+ } finally {
+ stateLock.unlock();
+ }
super.doStop();
}