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 e20062027266 CAMEL-27321: camel-jms, camel-sjms - every InOut request
completes when the reply manager stops (#30575)
e20062027266 is described below
commit e20062027266fdc4e81865b1325a804084a3253f
Author: allthingssecurity <[email protected]>
AuthorDate: Sun Nov 22 19:09:41 2026 +0530
CAMEL-27321: camel-jms, camel-sjms - every InOut request completes when the
reply manager stops (#30575)
Follow-up of CAMEL-24124, which completes the exchanges that wait for a
reply
when the reply manager stops. Some were still never completed:
- a request registered between the drain and the clear of the correlation
map, or after the stop, and a handler moved to its JMSMessageID after the
drain (useMessageIDAsCorrelationID): the map does not check that it
stopped;
- timeout tasks still queued when the forced shutdown of the onTimeout
executor drops them;
- a timeout task rejected by the executor (rejectedPolicy=Abort), which
DefaultTimeoutMap swallowed without a log.
The correlation map is now closed under its lock before the drain: a new
request is refused (the producer completes the exchange with a
RejectedExecutionException and does not send it), and a moved handler is
completed at once. Each timeout task runs once: a rejected one runs in the
calling thread, and the ones the executor did not run are completed by the
reply manager after the executor shutdown. DefaultTimeoutMap logs an
exception
of a listener at WARN.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../component/jms/reply/CorrelationTimeoutMap.java | 125 ++++++++++-
.../component/jms/reply/ReplyManagerSupport.java | 5 +
.../ReplyManagerStopCompletesRequestsTest.java | 249 +++++++++++++++++++++
.../sjms/reply/CorrelationTimeoutMap.java | 125 ++++++++++-
.../component/sjms/reply/ReplyManagerSupport.java | 5 +
.../ReplyManagerStopCompletesRequestsTest.java | 249 +++++++++++++++++++++
.../apache/camel/support/DefaultTimeoutMap.java | 4 +-
7 files changed, 753 insertions(+), 9 deletions(-)
diff --git
a/components/camel-jms/src/main/java/org/apache/camel/component/jms/reply/CorrelationTimeoutMap.java
b/components/camel-jms/src/main/java/org/apache/camel/component/jms/reply/CorrelationTimeoutMap.java
index efd5316f6ba2..f403933ac1c3 100644
---
a/components/camel-jms/src/main/java/org/apache/camel/component/jms/reply/CorrelationTimeoutMap.java
+++
b/components/camel-jms/src/main/java/org/apache/camel/component/jms/reply/CorrelationTimeoutMap.java
@@ -16,8 +16,14 @@
*/
package org.apache.camel.component.jms.reply;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
+import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
import org.apache.camel.support.DefaultTimeoutMap;
@@ -28,17 +34,33 @@ import static org.apache.camel.TimeoutMap.Listener.Type.*;
* A {@link org.apache.camel.TimeoutMap} which is used to track reply messages
which has been timed out, and thus should
* trigger the waiting {@link org.apache.camel.Exchange} to timeout as well.
Zero (or negative) timeout means infinite
* but is actually encoded as {@link Integer#MAX_VALUE} which is 24 days.
+ * <p/>
+ * Every handler that is added to the map is completed once: by its reply, by
its timeout, or when the map stops. Once
+ * the map has stopped, no handler is added any more: registering a new reply
is refused, and a handler that is moved to
+ * another correlation id (the JMSMessageID) is completed at once.
*/
class CorrelationTimeoutMap extends DefaultTimeoutMap<String, ReplyHandler> {
+ // the lock of the map, which also guards closed
+ private final Lock lock;
private final BiConsumer<ReplyHandler, String> evictionTask;
+ // the onTimeout tasks handed to the executor that have not started yet
+ private final Set<EvictionTask> pendingEvictions =
ConcurrentHashMap.newKeySet();
+ // set when the map stops, before the drain, so a handler can no longer be
added after the drain
+ private boolean closed;
CorrelationTimeoutMap(ScheduledExecutorService executor, long
requestMapPollTimeMillis, ExecutorService executorService) {
- super(executor, requestMapPollTimeMillis);
+ this(executor, requestMapPollTimeMillis, executorService, new
ReentrantLock());
+ }
+
+ private CorrelationTimeoutMap(ScheduledExecutorService executor, long
requestMapPollTimeMillis,
+ ExecutorService executorService, Lock lock) {
+ super(executor, requestMapPollTimeMillis, lock);
+ this.lock = lock;
// Support synchronous or asynchronous handling of evictions
evictionTask = executorService == null
? ReplyHandler::onTimeout
- : (handler, key) -> executorService.submit(() ->
handler.onTimeout(key));
+ : (handler, key) -> submitEviction(executorService, handler,
key);
addListener(this::listener);
}
@@ -57,20 +79,115 @@ class CorrelationTimeoutMap extends
DefaultTimeoutMap<String, ReplyHandler> {
}
}
+ private void submitEviction(ExecutorService executorService, ReplyHandler
handler, String key) {
+ EvictionTask task = new EvictionTask(handler, key);
+ pendingEvictions.add(task);
+ try {
+ executorService.submit(task);
+ } catch (RejectedExecutionException e) {
+ // such as with rejectedPolicy=Abort and a full queue: the entry
is no longer in the map, so nothing else
+ // would complete the exchange; run the task here as the
CallerRuns policy does
+ log.warn("The timeout task of correlationID: {} was rejected by
the executor ({}). Running it in the calling"
+ + " thread instead.",
+ key, e.getMessage());
+ task.run();
+ }
+ }
+
+ /**
+ * Completes the exchanges whose timeout task was handed to the executor
but not run by it, such as the tasks that
+ * were still queued when the executor was shut down (a forced shutdown
drops them). The reply manager calls this
+ * after it has shut down the executor. Each task runs at most once.
+ */
+ void completePendingEvictions() {
+ int size = pendingEvictions.size();
+ if (size > 0) {
+ log.warn("Completing {} timed out requests whose timeout task was
not run before the executor was shut down",
+ size);
+ for (EvictionTask task : pendingEvictions) {
+ task.run();
+ }
+ }
+ }
+
+ @Override
+ protected void doStart() throws Exception {
+ lock.lock();
+ try {
+ closed = false;
+ } finally {
+ lock.unlock();
+ }
+ super.doStart();
+ }
+
@Override
protected void doStop() throws Exception {
+ // close the map before the drain: a handler added after the drain
would be cleared by super.doStop() (or stay
+ // in the stopped map), and its exchange would never complete
+ lock.lock();
+ try {
+ closed = true;
+ } finally {
+ lock.unlock();
+ }
drainAndEvictAll();
super.doStop();
}
@Override
public ReplyHandler put(String key, ReplyHandler value, long
timeoutMillis) {
- return super.put(key, value, encode(timeoutMillis));
+ lock.lock();
+ try {
+ if (!closed) {
+ return super.put(key, value, encode(timeoutMillis));
+ }
+ } finally {
+ lock.unlock();
+ }
+ // the map has stopped and was drained: this handler (moved to another
correlation id after the drain) is in
+ // no map any more, so it is completed here as the drain would have
done
+ log.debug("Cannot add correlationID: {} as the reply manager is
stopped. Completing its exchange.", key);
+ value.onTimeout(key);
+ return null;
}
@Override
public ReplyHandler putIfAbsent(String key, ReplyHandler value, long
timeoutMillis) {
- return super.putIfAbsent(key, value, encode(timeoutMillis));
+ lock.lock();
+ try {
+ if (closed) {
+ throw new RejectedExecutionException(
+ "Cannot wait for the reply with correlationID: " + key
+ " as the reply manager is stopped");
+ }
+ return super.putIfAbsent(key, value, encode(timeoutMillis));
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * The timeout task of a handler, which runs once: on the executor, in the
calling thread when the executor rejects
+ * it, or from {@link #completePendingEvictions()} when the executor never
ran it.
+ */
+ private final class EvictionTask implements Runnable {
+
+ private final ReplyHandler handler;
+ private final String key;
+ private final AtomicBoolean claimed = new AtomicBoolean();
+
+ EvictionTask(ReplyHandler handler, String key) {
+ this.handler = handler;
+ this.key = key;
+ }
+
+ @Override
+ public void run() {
+ if (claimed.compareAndSet(false, true)) {
+ pendingEvictions.remove(this);
+ handler.onTimeout(key);
+ }
+ }
}
}
diff --git
a/components/camel-jms/src/main/java/org/apache/camel/component/jms/reply/ReplyManagerSupport.java
b/components/camel-jms/src/main/java/org/apache/camel/component/jms/reply/ReplyManagerSupport.java
index 9dd887a9aba5..4061f83c5cf7 100644
---
a/components/camel-jms/src/main/java/org/apache/camel/component/jms/reply/ReplyManagerSupport.java
+++
b/components/camel-jms/src/main/java/org/apache/camel/component/jms/reply/ReplyManagerSupport.java
@@ -341,6 +341,11 @@ public abstract class ReplyManagerSupport extends
ServiceSupport implements Repl
camelContext.getExecutorServiceManager().shutdownGraceful(executorService);
executorService = null;
}
+ // a timeout task the executor did not run (a forced shutdown drops
the queued ones) must still complete its
+ // exchange, which would otherwise never complete
+ if (correlation != null) {
+ correlation.completePendingEvictions();
+ }
}
protected static void setupClientId(JmsEndpoint endpoint,
DefaultMessageListenerContainer answer) {
diff --git
a/components/camel-jms/src/test/java/org/apache/camel/component/jms/reply/ReplyManagerStopCompletesRequestsTest.java
b/components/camel-jms/src/test/java/org/apache/camel/component/jms/reply/ReplyManagerStopCompletesRequestsTest.java
new file mode 100644
index 000000000000..aff053beb887
--- /dev/null
+++
b/components/camel-jms/src/test/java/org/apache/camel/component/jms/reply/ReplyManagerStopCompletesRequestsTest.java
@@ -0,0 +1,249 @@
+/*
+ * 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.component.jms.reply;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.CamelContext;
+import org.apache.camel.TimeoutMap;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.ThreadPoolProfile;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.util.concurrent.ThreadPoolRejectedPolicy;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.awaitility.Awaitility.await;
+
+/**
+ * Every request registered with a reply manager completes exactly once, also
when the reply manager stops while a
+ * producer registers it or moves it to its JMSMessageID, when the stop drops
the queued timeout tasks, and when the
+ * executor rejects a timeout task. The reply manager is set up as JmsProducer
does it, without a broker: these paths do
+ * not involve the listener container.
+ */
+class ReplyManagerStopCompletesRequestsTest {
+
+ private final Map<String, AtomicInteger> done = new ConcurrentHashMap<>();
+ private CamelContext context;
+
+ @BeforeEach
+ void startContext() {
+ context = new DefaultCamelContext();
+ context.start();
+ }
+
+ @AfterEach
+ void stopContext() {
+ context.stop();
+ }
+
+ private QueueReplyManager newReplyManager(String name, ExecutorService
onTimeout) {
+ QueueReplyManager replyManager = new QueueReplyManager(context);
+ ScheduledExecutorService checker = context.getExecutorServiceManager()
+ .newSingleThreadScheduledExecutor(replyManager,
"JmsReplyManagerTimeoutChecker[" + name + "]");
+ ExecutorService executor = onTimeout != null
+ ? onTimeout
+ :
context.getExecutorServiceManager().newThreadPool(replyManager,
"JmsReplyManagerOnTimeout[" + name + "]",
+ 0, 1);
+ replyManager.setScheduledExecutorService(checker);
+ replyManager.setOnTimeoutExecutorService(executor);
+ // what ReplyManagerSupport.doStart does for the correlation map (the
listener container needs a broker)
+ replyManager.correlation = new CorrelationTimeoutMap(checker, 50,
executor);
+ replyManager.correlation.start();
+ return replyManager;
+ }
+
+ private AsyncCallback callback(String name, Runnable onDone) {
+ AtomicInteger counter = new AtomicInteger();
+ done.put(name, counter);
+ return doneSync -> {
+ counter.incrementAndGet();
+ if (onDone != null) {
+ onDone.run();
+ }
+ };
+ }
+
+ private void register(QueueReplyManager replyManager, String
correlationId, long timeout, Runnable onDone) {
+ replyManager.registerReply(replyManager, new DefaultExchange(context),
callback(correlationId, onDone), null,
+ correlationId, timeout);
+ }
+
+ private int done(String name) {
+ return done.get(name).get();
+ }
+
+ private static void awaitLatch(CountDownLatch latch) {
+ try {
+ latch.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ @Test
+ void registerAfterStopIsRefused() throws Exception {
+ QueueReplyManager replyManager = newReplyManager("after", null);
+ replyManager.doStop();
+
+ // the producer completes the exchange with this exception (the
request is not sent)
+ assertThatThrownBy(() -> register(replyManager, "late", 200, null))
+ .isInstanceOf(RejectedExecutionException.class);
+ assertThat(replyManager.correlation.size()).isZero();
+ assertThat(done("late")).isZero();
+ }
+
+ @Test
+ void registerWhileStopDrainsIsRefused() throws Exception {
+ QueueReplyManager replyManager = newReplyManager("drain", null);
+ CountDownLatch draining = new CountDownLatch(1);
+ CountDownLatch registered = new CountDownLatch(1);
+ replyManager.correlation.addListener((type, key, value) -> {
+ if (type == TimeoutMap.Listener.Type.Evict &&
key.equals("pending")) {
+ // the stop has drained the map and is about to clear it
+ draining.countDown();
+ awaitLatch(registered);
+ }
+ });
+ register(replyManager, "pending", 60000, null);
+
+ AtomicReference<Exception> refused = new AtomicReference<>();
+ Thread producer = new Thread(() -> {
+ awaitLatch(draining);
+ try {
+ register(replyManager, "in-flight", 200, null);
+ } catch (Exception e) {
+ refused.set(e);
+ } finally {
+ registered.countDown();
+ }
+ }, "producer");
+ producer.start();
+
+ replyManager.doStop();
+ producer.join(10000);
+
+ // the request registered during the stop is refused, so the producer
completes its exchange; before, it was
+ // cleared from the map with no event and never completed
+
assertThat(refused.get()).isInstanceOf(RejectedExecutionException.class);
+ assertThat(done("in-flight")).isZero();
+ assertThat(replyManager.correlation.size()).isZero();
+ await().atMost(5, TimeUnit.SECONDS).until(() -> done("pending") == 1);
+ }
+
+ @Test
+ void movedToMessageIdAfterTheDrainIsCompleted() throws Exception {
+ QueueReplyManager replyManager = newReplyManager("msgid", null);
+ CountDownLatch removed = new CountDownLatch(1);
+ CountDownLatch stopped = new CountDownLatch(1);
+ replyManager.correlation.addListener((type, key, value) -> {
+ if (type == TimeoutMap.Listener.Type.Remove &&
key.equals("provisional")) {
+ // the producer is in updateCorrelationId, between the remove
and the put
+ removed.countDown();
+ awaitLatch(stopped);
+ }
+ });
+ register(replyManager, "provisional", 60000, null);
+
+ Thread producer = new Thread(
+ () -> replyManager.updateCorrelationId("provisional",
"ID:broker-1", 60000), "producer");
+ producer.start();
+ awaitLatch(removed);
+ replyManager.doStop();
+ stopped.countDown();
+ producer.join(10000);
+
+ // the handler was in no map during the drain: it is completed when it
is put into the stopped map
+ assertThat(done("provisional")).isEqualTo(1);
+ assertThat(replyManager.correlation.size()).isZero();
+ }
+
+ @Test
+ void timeoutTasksDroppedByForcedShutdownAreCompleted() throws Exception {
+ context.getExecutorServiceManager().setShutdownAwaitTermination(300);
+ QueueReplyManager replyManager = newReplyManager("forced", null);
+ // the first exchange that continues routing on the single timeout
thread is slow, so the other one is still
+ // queued when the forced shutdown drops the queue
+ AtomicBoolean first = new AtomicBoolean();
+ CountDownLatch never = new CountDownLatch(1);
+ Runnable slowOnce = () -> {
+ if (first.compareAndSet(false, true)) {
+ awaitLatch(never);
+ }
+ };
+ register(replyManager, "a", 60000, slowOnce);
+ register(replyManager, "b", 60000, slowOnce);
+
+ replyManager.doStop();
+
+ assertThat(done("a")).isEqualTo(1);
+ assertThat(done("b")).isEqualTo(1);
+ }
+
+ @Test
+ void rejectedTimeoutTaskRunsInTheCallingThread() throws Exception {
+ // as camel.threadpool.rejectedPolicy=Abort does, with a small queue
+ ThreadPoolProfile profile = new ThreadPoolProfile("abort");
+ profile.setPoolSize(1);
+ profile.setMaxPoolSize(1);
+ profile.setMaxQueueSize(1);
+ profile.setRejectedPolicy(ThreadPoolRejectedPolicy.Abort);
+ ExecutorService executor =
context.getExecutorServiceManager().newThreadPool(this, "OnTimeoutAbort",
profile);
+ QueueReplyManager replyManager = newReplyManager("abort", executor);
+ AtomicInteger evicted = new AtomicInteger();
+ // added after the map's own listener, so it counts the timeout tasks
already handed to the executor
+ replyManager.correlation.addListener((type, key, value) -> {
+ if (type == TimeoutMap.Listener.Type.Evict) {
+ evicted.incrementAndGet();
+ }
+ });
+ // the first timeout task holds the only thread, the second fills the
queue, the third is rejected
+ AtomicBoolean first = new AtomicBoolean();
+ CountDownLatch release = new CountDownLatch(1);
+ Runnable blockOnce = () -> {
+ if (first.compareAndSet(false, true)) {
+ awaitLatch(release);
+ }
+ };
+ register(replyManager, "t1", 100, blockOnce);
+ register(replyManager, "t2", 100, blockOnce);
+ register(replyManager, "t3", 100, blockOnce);
+
+ await().atMost(10, TimeUnit.SECONDS).until(() -> evicted.get() == 3);
+ release.countDown();
+
+ await().atMost(10, TimeUnit.SECONDS)
+ .until(() -> done("t1") + done("t2") + done("t3") == 3);
+ assertThat(done("t1")).isEqualTo(1);
+ assertThat(done("t2")).isEqualTo(1);
+ assertThat(done("t3")).isEqualTo(1);
+ replyManager.doStop();
+ }
+}
diff --git
a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/CorrelationTimeoutMap.java
b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/CorrelationTimeoutMap.java
index 632a0413b67c..8c9fbe752378 100644
---
a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/CorrelationTimeoutMap.java
+++
b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/CorrelationTimeoutMap.java
@@ -16,8 +16,14 @@
*/
package org.apache.camel.component.sjms.reply;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
+import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
import org.apache.camel.support.DefaultTimeoutMap;
@@ -28,17 +34,33 @@ import static org.apache.camel.TimeoutMap.Listener.Type.*;
* A {@link org.apache.camel.TimeoutMap} which is used to track reply messages
which has been timed out, and thus should
* trigger the waiting {@link org.apache.camel.Exchange} to timeout as well.
Zero (or negative) timeout means infinite
* but is actually encoded as {@link Integer#MAX_VALUE} which is 24 days.
+ * <p/>
+ * Every handler that is added to the map is completed once: by its reply, by
its timeout, or when the map stops. Once
+ * the map has stopped, no handler is added any more: registering a new reply
is refused, and a handler that is moved to
+ * another correlation id (the JMSMessageID) is completed at once.
*/
class CorrelationTimeoutMap extends DefaultTimeoutMap<String, ReplyHandler> {
+ // the lock of the map, which also guards closed
+ private final Lock lock;
private final BiConsumer<ReplyHandler, String> evictionTask;
+ // the onTimeout tasks handed to the executor that have not started yet
+ private final Set<EvictionTask> pendingEvictions =
ConcurrentHashMap.newKeySet();
+ // set when the map stops, before the drain, so a handler can no longer be
added after the drain
+ private boolean closed;
CorrelationTimeoutMap(ScheduledExecutorService executor, long
requestMapPollTimeMillis, ExecutorService executorService) {
- super(executor, requestMapPollTimeMillis);
+ this(executor, requestMapPollTimeMillis, executorService, new
ReentrantLock());
+ }
+
+ private CorrelationTimeoutMap(ScheduledExecutorService executor, long
requestMapPollTimeMillis,
+ ExecutorService executorService, Lock lock) {
+ super(executor, requestMapPollTimeMillis, lock);
+ this.lock = lock;
// Support synchronous or asynchronous handling of evictions
evictionTask = executorService == null
? ReplyHandler::onTimeout
- : (handler, key) -> executorService.submit(() ->
handler.onTimeout(key));
+ : (handler, key) -> submitEviction(executorService, handler,
key);
addListener(this::listener);
}
@@ -57,20 +79,115 @@ class CorrelationTimeoutMap extends
DefaultTimeoutMap<String, ReplyHandler> {
}
}
+ private void submitEviction(ExecutorService executorService, ReplyHandler
handler, String key) {
+ EvictionTask task = new EvictionTask(handler, key);
+ pendingEvictions.add(task);
+ try {
+ executorService.submit(task);
+ } catch (RejectedExecutionException e) {
+ // such as with rejectedPolicy=Abort and a full queue: the entry
is no longer in the map, so nothing else
+ // would complete the exchange; run the task here as the
CallerRuns policy does
+ log.warn("The timeout task of correlationID: {} was rejected by
the executor ({}). Running it in the calling"
+ + " thread instead.",
+ key, e.getMessage());
+ task.run();
+ }
+ }
+
+ /**
+ * Completes the exchanges whose timeout task was handed to the executor
but not run by it, such as the tasks that
+ * were still queued when the executor was shut down (a forced shutdown
drops them). The reply manager calls this
+ * after it has shut down the executor. Each task runs at most once.
+ */
+ void completePendingEvictions() {
+ int size = pendingEvictions.size();
+ if (size > 0) {
+ log.warn("Completing {} timed out requests whose timeout task was
not run before the executor was shut down",
+ size);
+ for (EvictionTask task : pendingEvictions) {
+ task.run();
+ }
+ }
+ }
+
+ @Override
+ protected void doStart() throws Exception {
+ lock.lock();
+ try {
+ closed = false;
+ } finally {
+ lock.unlock();
+ }
+ super.doStart();
+ }
+
@Override
protected void doStop() throws Exception {
+ // close the map before the drain: a handler added after the drain
would be cleared by super.doStop() (or stay
+ // in the stopped map), and its exchange would never complete
+ lock.lock();
+ try {
+ closed = true;
+ } finally {
+ lock.unlock();
+ }
drainAndEvictAll();
super.doStop();
}
@Override
public ReplyHandler put(String key, ReplyHandler value, long
timeoutMillis) {
- return super.put(key, value, encode(timeoutMillis));
+ lock.lock();
+ try {
+ if (!closed) {
+ return super.put(key, value, encode(timeoutMillis));
+ }
+ } finally {
+ lock.unlock();
+ }
+ // the map has stopped and was drained: this handler (moved to another
correlation id after the drain) is in
+ // no map any more, so it is completed here as the drain would have
done
+ log.debug("Cannot add correlationID: {} as the reply manager is
stopped. Completing its exchange.", key);
+ value.onTimeout(key);
+ return null;
}
@Override
public ReplyHandler putIfAbsent(String key, ReplyHandler value, long
timeoutMillis) {
- return super.putIfAbsent(key, value, encode(timeoutMillis));
+ lock.lock();
+ try {
+ if (closed) {
+ throw new RejectedExecutionException(
+ "Cannot wait for the reply with correlationID: " + key
+ " as the reply manager is stopped");
+ }
+ return super.putIfAbsent(key, value, encode(timeoutMillis));
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * The timeout task of a handler, which runs once: on the executor, in the
calling thread when the executor rejects
+ * it, or from {@link #completePendingEvictions()} when the executor never
ran it.
+ */
+ private final class EvictionTask implements Runnable {
+
+ private final ReplyHandler handler;
+ private final String key;
+ private final AtomicBoolean claimed = new AtomicBoolean();
+
+ EvictionTask(ReplyHandler handler, String key) {
+ this.handler = handler;
+ this.key = key;
+ }
+
+ @Override
+ public void run() {
+ if (claimed.compareAndSet(false, true)) {
+ pendingEvictions.remove(this);
+ handler.onTimeout(key);
+ }
+ }
}
}
diff --git
a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/ReplyManagerSupport.java
b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/ReplyManagerSupport.java
index 81a88d5fd67b..653f43a06bd8 100644
---
a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/ReplyManagerSupport.java
+++
b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/ReplyManagerSupport.java
@@ -273,6 +273,11 @@ public abstract class ReplyManagerSupport extends
ServiceSupport implements Repl
camelContext.getExecutorServiceManager().shutdownGraceful(executorService);
executorService = null;
}
+ // a timeout task the executor did not run (a forced shutdown drops
the queued ones) must still complete its
+ // exchange, which would otherwise never complete
+ if (correlation != null) {
+ correlation.completePendingEvictions();
+ }
}
}
diff --git
a/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/reply/ReplyManagerStopCompletesRequestsTest.java
b/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/reply/ReplyManagerStopCompletesRequestsTest.java
new file mode 100644
index 000000000000..47167d244cc5
--- /dev/null
+++
b/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/reply/ReplyManagerStopCompletesRequestsTest.java
@@ -0,0 +1,249 @@
+/*
+ * 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.component.sjms.reply;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.CamelContext;
+import org.apache.camel.TimeoutMap;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.ThreadPoolProfile;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.util.concurrent.ThreadPoolRejectedPolicy;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+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.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * Every request registered with a reply manager completes exactly once, also
when the reply manager stops while a
+ * producer registers it or moves it to its JMSMessageID, when the stop drops
the queued timeout tasks, and when the
+ * executor rejects a timeout task. The reply manager is set up as
SjmsProducer does it, without a broker: these paths
+ * do not involve the listener container.
+ */
+class ReplyManagerStopCompletesRequestsTest {
+
+ private final Map<String, AtomicInteger> done = new ConcurrentHashMap<>();
+ private CamelContext context;
+
+ @BeforeEach
+ void startContext() {
+ context = new DefaultCamelContext();
+ context.start();
+ }
+
+ @AfterEach
+ void stopContext() {
+ context.stop();
+ }
+
+ private QueueReplyManager newReplyManager(String name, ExecutorService
onTimeout) {
+ QueueReplyManager replyManager = new QueueReplyManager(context);
+ ScheduledExecutorService checker = context.getExecutorServiceManager()
+ .newSingleThreadScheduledExecutor(replyManager,
"JmsReplyManagerTimeoutChecker[" + name + "]");
+ ExecutorService executor = onTimeout != null
+ ? onTimeout
+ :
context.getExecutorServiceManager().newThreadPool(replyManager,
"JmsReplyManagerOnTimeout[" + name + "]",
+ 0, 1);
+ replyManager.setScheduledExecutorService(checker);
+ replyManager.setOnTimeoutExecutorService(executor);
+ // what ReplyManagerSupport.doStart does for the correlation map (the
listener container needs a broker)
+ replyManager.correlation = new CorrelationTimeoutMap(checker, 50,
executor);
+ replyManager.correlation.start();
+ return replyManager;
+ }
+
+ private AsyncCallback callback(String name, Runnable onDone) {
+ AtomicInteger counter = new AtomicInteger();
+ done.put(name, counter);
+ return doneSync -> {
+ counter.incrementAndGet();
+ if (onDone != null) {
+ onDone.run();
+ }
+ };
+ }
+
+ private void register(QueueReplyManager replyManager, String
correlationId, long timeout, Runnable onDone) {
+ replyManager.registerReply(replyManager, new DefaultExchange(context),
callback(correlationId, onDone), null,
+ correlationId, timeout);
+ }
+
+ private int done(String name) {
+ return done.get(name).get();
+ }
+
+ private static void awaitLatch(CountDownLatch latch) {
+ try {
+ latch.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ @Test
+ void registerAfterStopIsRefused() throws Exception {
+ QueueReplyManager replyManager = newReplyManager("after", null);
+ replyManager.doStop();
+
+ // the producer completes the exchange with this exception (the
request is not sent)
+ assertThrows(RejectedExecutionException.class, () ->
register(replyManager, "late", 200, null));
+ assertEquals(0, replyManager.correlation.size());
+ assertEquals(0, done("late"));
+ }
+
+ @Test
+ void registerWhileStopDrainsIsRefused() throws Exception {
+ QueueReplyManager replyManager = newReplyManager("drain", null);
+ CountDownLatch draining = new CountDownLatch(1);
+ CountDownLatch registered = new CountDownLatch(1);
+ replyManager.correlation.addListener((type, key, value) -> {
+ if (type == TimeoutMap.Listener.Type.Evict &&
key.equals("pending")) {
+ // the stop has drained the map and is about to clear it
+ draining.countDown();
+ awaitLatch(registered);
+ }
+ });
+ register(replyManager, "pending", 60000, null);
+
+ AtomicReference<Exception> refused = new AtomicReference<>();
+ Thread producer = new Thread(() -> {
+ awaitLatch(draining);
+ try {
+ register(replyManager, "in-flight", 200, null);
+ } catch (Exception e) {
+ refused.set(e);
+ } finally {
+ registered.countDown();
+ }
+ }, "producer");
+ producer.start();
+
+ replyManager.doStop();
+ producer.join(10000);
+
+ // the request registered during the stop is refused, so the producer
completes its exchange; before, it was
+ // cleared from the map with no event and never completed
+ assertInstanceOf(RejectedExecutionException.class, refused.get());
+ assertEquals(0, done("in-flight"));
+ assertEquals(0, replyManager.correlation.size());
+ await().atMost(5, TimeUnit.SECONDS).until(() -> done("pending") == 1);
+ }
+
+ @Test
+ void movedToMessageIdAfterTheDrainIsCompleted() throws Exception {
+ QueueReplyManager replyManager = newReplyManager("msgid", null);
+ CountDownLatch removed = new CountDownLatch(1);
+ CountDownLatch stopped = new CountDownLatch(1);
+ replyManager.correlation.addListener((type, key, value) -> {
+ if (type == TimeoutMap.Listener.Type.Remove &&
key.equals("provisional")) {
+ // the producer is in updateCorrelationId, between the remove
and the put
+ removed.countDown();
+ awaitLatch(stopped);
+ }
+ });
+ register(replyManager, "provisional", 60000, null);
+
+ Thread producer = new Thread(
+ () -> replyManager.updateCorrelationId("provisional",
"ID:broker-1", 60000), "producer");
+ producer.start();
+ awaitLatch(removed);
+ replyManager.doStop();
+ stopped.countDown();
+ producer.join(10000);
+
+ // the handler was in no map during the drain: it is completed when it
is put into the stopped map
+ assertEquals(1, done("provisional"));
+ assertEquals(0, replyManager.correlation.size());
+ }
+
+ @Test
+ void timeoutTasksDroppedByForcedShutdownAreCompleted() throws Exception {
+ context.getExecutorServiceManager().setShutdownAwaitTermination(300);
+ QueueReplyManager replyManager = newReplyManager("forced", null);
+ // the first exchange that continues routing on the single timeout
thread is slow, so the other one is still
+ // queued when the forced shutdown drops the queue
+ AtomicBoolean first = new AtomicBoolean();
+ CountDownLatch never = new CountDownLatch(1);
+ Runnable slowOnce = () -> {
+ if (first.compareAndSet(false, true)) {
+ awaitLatch(never);
+ }
+ };
+ register(replyManager, "a", 60000, slowOnce);
+ register(replyManager, "b", 60000, slowOnce);
+
+ replyManager.doStop();
+
+ assertEquals(1, done("a"));
+ assertEquals(1, done("b"));
+ }
+
+ @Test
+ void rejectedTimeoutTaskRunsInTheCallingThread() throws Exception {
+ // as camel.threadpool.rejectedPolicy=Abort does, with a small queue
+ ThreadPoolProfile profile = new ThreadPoolProfile("abort");
+ profile.setPoolSize(1);
+ profile.setMaxPoolSize(1);
+ profile.setMaxQueueSize(1);
+ profile.setRejectedPolicy(ThreadPoolRejectedPolicy.Abort);
+ ExecutorService executor =
context.getExecutorServiceManager().newThreadPool(this, "OnTimeoutAbort",
profile);
+ QueueReplyManager replyManager = newReplyManager("abort", executor);
+ AtomicInteger evicted = new AtomicInteger();
+ // added after the map's own listener, so it counts the timeout tasks
already handed to the executor
+ replyManager.correlation.addListener((type, key, value) -> {
+ if (type == TimeoutMap.Listener.Type.Evict) {
+ evicted.incrementAndGet();
+ }
+ });
+ // the first timeout task holds the only thread, the second fills the
queue, the third is rejected
+ AtomicBoolean first = new AtomicBoolean();
+ CountDownLatch release = new CountDownLatch(1);
+ Runnable blockOnce = () -> {
+ if (first.compareAndSet(false, true)) {
+ awaitLatch(release);
+ }
+ };
+ register(replyManager, "t1", 100, blockOnce);
+ register(replyManager, "t2", 100, blockOnce);
+ register(replyManager, "t3", 100, blockOnce);
+
+ await().atMost(10, TimeUnit.SECONDS).until(() -> evicted.get() == 3);
+ release.countDown();
+
+ await().atMost(10, TimeUnit.SECONDS)
+ .until(() -> done("t1") + done("t2") + done("t3") == 3);
+ assertEquals(1, done("t1"));
+ assertEquals(1, done("t2"));
+ assertEquals(1, done("t3"));
+ replyManager.doStop();
+ }
+}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/DefaultTimeoutMap.java
b/core/camel-support/src/main/java/org/apache/camel/support/DefaultTimeoutMap.java
index 55a931cca17a..b4cb7f3209b5 100644
---
a/core/camel-support/src/main/java/org/apache/camel/support/DefaultTimeoutMap.java
+++
b/core/camel-support/src/main/java/org/apache/camel/support/DefaultTimeoutMap.java
@@ -255,7 +255,9 @@ public class DefaultTimeoutMap<K, V> extends ServiceSupport
implements TimeoutMa
log.warn("Error in a listener of the timeout map for key: {}
({} event). This error is ignored.", key, type,
t);
} catch (Exception t) {
- // Ignore
+ // nothing else sees an exception of a listener (an evicted
entry is no longer in the map): log it
+ log.warn("Exception in a listener of the timeout map for key:
{} ({} event). This exception is ignored.",
+ key, type, t);
}
}
}