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 40e30853deb9 CAMEL-27416: camel-base-engine -
AsyncProcessorAwaitManager: an interrupt leaves a returned exchange alone, and
every waiting thread stays listed (#30759)
40e30853deb9 is described below
commit 40e30853deb90efd44e51650ec0883e8675a929c
Author: allthingssecurity <[email protected]>
AuthorDate: Wed Nov 25 16:45:49 2026 +0530
CAMEL-27416: camel-base-engine - AsyncProcessorAwaitManager: an interrupt
leaves a returned exchange alone, and every waiting thread stays listed (#30759)
interrupt(exchange) read the entry of the blocked thread, made the WARN
line, and only then failed the exchange and counted the latch down. When
the callback fired in between, the thread had already returned the
exchange as done, and the interrupt then marked it failed and interrupted
while its caller went on with it.
The entries were kept by exchange, so a second thread that waited for the
same exchange replaced the entry of the first and removed it when it
returned: the first thread was no longer listed, and neither JMX nor the
stop could interrupt it. doStop also cleared the entries it had not
interrupted.
There is now one entry per waiting thread. The entry decides under its
own lock whether the interrupt still applies (the thread has not
returned and the callback has not fired), and the thread marks the entry
finished under that lock before it returns. interrupt(exchange)
interrupts every thread that waits for the exchange. doStop no longer
clears the entries: each thread removes its own.
Found with a TLA+ model.
Also in this change:
- CAMEL-27416: camel-base-engine - review follow-up: interrupt(exchange)
releases only the innermost waiter
- CAMEL-27416: camel-base-engine - review follow-up: per-exchange order of
waiters
- CAMEL-27416: camel-api - upgrade guide entry for the new
ExchangeExtension method
- CAMEL-27416: camel-api - Javadoc: @since 4.24 and why a plain counter is
safe for nextAwaitOrder(), shorter sentences for interrupt
- CAMEL-27416: camel-base-engine - review follow-up: upgrade guide and
Javadoc wording, test name, tracked worker thread
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../java/org/apache/camel/ExchangeExtension.java | 14 +
.../camel/spi/AsyncProcessorAwaitManager.java | 11 +
.../engine/DefaultAsyncProcessorAwaitManager.java | 155 +++++++--
...syncProcessorAwaitManagerInterruptRaceTest.java | 371 +++++++++++++++++++++
.../org/apache/camel/support/AbstractExchange.java | 7 +
.../camel/support/ExtendedExchangeExtension.java | 6 +
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 18 +
7 files changed, 545 insertions(+), 37 deletions(-)
diff --git
a/core/camel-api/src/main/java/org/apache/camel/ExchangeExtension.java
b/core/camel-api/src/main/java/org/apache/camel/ExchangeExtension.java
index 6ed39f6a7b86..bf0556764875 100644
--- a/core/camel-api/src/main/java/org/apache/camel/ExchangeExtension.java
+++ b/core/camel-api/src/main/java/org/apache/camel/ExchangeExtension.java
@@ -143,6 +143,20 @@ public interface ExchangeExtension {
*/
void setInterrupted(boolean interrupted);
+ /**
+ * Used by the {@link org.apache.camel.spi.AsyncProcessorAwaitManager}
each time its process() is called for this
+ * exchange (whether or not the thread then waits): returns a number one
higher than the previous call for this
+ * exchange, so the manager knows which of the threads that wait for the
exchange called it last. This is used
+ * internally by Camel.
+ * <p>
+ * The calls for one exchange do not overlap: an inner call is made while
the outer call processes the exchange,
+ * after the exchange was handed to another thread, and that hand-off
orders the two calls. So an implementation can
+ * use a plain counter.
+ *
+ * @since 4.24
+ */
+ long nextAwaitOrder();
+
/**
* Whether the exchange has exhausted (attempted all) its redeliveries and
still failed. This is used internally by
* Camel.
diff --git
a/core/camel-api/src/main/java/org/apache/camel/spi/AsyncProcessorAwaitManager.java
b/core/camel-api/src/main/java/org/apache/camel/spi/AsyncProcessorAwaitManager.java
index dd2d03ec671c..b4d51d88595e 100644
---
a/core/camel-api/src/main/java/org/apache/camel/spi/AsyncProcessorAwaitManager.java
+++
b/core/camel-api/src/main/java/org/apache/camel/spi/AsyncProcessorAwaitManager.java
@@ -163,6 +163,9 @@ public interface AsyncProcessorAwaitManager extends
StaticService {
* Though if it appears as the exchange is <i>stuck</i>, then this method
can remedy this, by forcing the latch to
* count-down so the blocked thread can continue. An exception is set on
the exchange which allows Camel's error
* handler to deal with this malfunctioned exchange.
+ * <p>
+ * When more than one thread waits for the exchange, only the thread whose
+ * {@link #process(AsyncProcessor, Exchange)} call started last is
released, see {@link #interrupt(Exchange)}.
*
* @param exchangeId the exchange id to interrupt.
*/
@@ -176,6 +179,14 @@ public interface AsyncProcessorAwaitManager extends
StaticService {
* Though if it appears as the exchange is <i>stuck</i>, then this method
can remedy this, by forcing the latch to
* count-down so the blocked thread can continue. An exception is set on
the exchange which allows Camel's error
* handler to deal with this malfunctioned exchange.
+ * <p>
+ * When more than one thread waits for the exchange, only the thread whose
+ * {@link #process(AsyncProcessor, Exchange)} call started last is
released. This happens in a nested wait. One
+ * thread waits for the exchange. On another thread, the exchange then
enters a step that waits for it too (such as
+ * {@code ProducerTemplate.send(uri, exchange)}). The released inner
thread goes on with the failed exchange to the
+ * end of its route, and the callback then releases the outer thread. So
an interrupt never releases both threads of
+ * a nested wait. Stopping the manager, with {@link
#isInterruptThreadsWhileStopping()}, releases every blocked
+ * thread.
*
* @param exchange the exchange to interrupt.
*/
diff --git
a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultAsyncProcessorAwaitManager.java
b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultAsyncProcessorAwaitManager.java
index 5291ceba2c33..2e3c3e5b0028 100644
---
a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultAsyncProcessorAwaitManager.java
+++
b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultAsyncProcessorAwaitManager.java
@@ -18,12 +18,14 @@ package org.apache.camel.impl.engine;
import java.util.Collection;
import java.util.Collections;
-import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
import org.apache.camel.AsyncCallback;
import org.apache.camel.AsyncProcessor;
@@ -53,7 +55,9 @@ public class DefaultAsyncProcessorAwaitManager extends
ServiceSupport implements
private final AtomicLong maxDuration = new AtomicLong();
private final AtomicLong meanDuration = new AtomicLong();
- private final Map<Exchange, AwaitThread> inflight = new
ConcurrentHashMap<>();
+ // one entry per waiting thread: two threads can wait for the same
exchange (a thread that waits for an exchange while
+ // the exchange goes on, on another thread, through a step that waits for
it too), and each must stay listed
+ private final Set<AwaitThreadEntry> inflight =
ConcurrentHashMap.newKeySet();
private final ExchangeFormatter exchangeFormatter;
private boolean interruptThreadsWhileStopping = true;
@@ -80,18 +84,26 @@ public class DefaultAsyncProcessorAwaitManager extends
ServiceSupport implements
*/
@Override
public void process(final AsyncProcessor processor, final Exchange
exchange) {
+ // the order of the calls for this exchange, so interrupt(exchange)
can find the innermost one: taken before the
+ // processor runs, as a nested call for the exchange starts from
within that processing (and so sees this number).
+ // It is kept on the exchange, as only the calls for the same exchange
are compared: no counter shared by all calls
+ long order = exchange.getExchangeExtension().nextAwaitOrder();
AwaitCallback callback = new AwaitCallback(exchange);
processor.process(exchange, callback);
// the callback has usually fired by now, as the reactive executor
runs the work in this thread
if (callback.get() == null) {
CountDownLatch latch = new CountDownLatch(1);
if (callback.compareAndSet(null, latch)) {
- await(exchange, latch);
+ await(exchange, latch, order);
}
}
}
public void await(Exchange exchange, CountDownLatch latch) {
+ await(exchange, latch,
exchange.getExchangeExtension().nextAwaitOrder());
+ }
+
+ private void await(Exchange exchange, CountDownLatch latch, long order) {
ReactiveExecutor reactiveExecutor =
exchange.getContext().getCamelContextExtension().getReactiveExecutor();
// Early exit for pending reactive queued work
do {
@@ -104,11 +116,12 @@ public class DefaultAsyncProcessorAwaitManager extends
ServiceSupport implements
LOG.trace("Waiting for asynchronous callback before continuing for
exchangeId: {} -> {}",
exchange.getExchangeId(), exchange);
}
+ AwaitThreadEntry entry = new AwaitThreadEntry(Thread.currentThread(),
exchange, latch, order);
try {
if (statistics.isStatisticsEnabled()) {
blockedCounter.incrementAndGet();
}
- inflight.put(exchange, new
AwaitThreadEntry(Thread.currentThread(), exchange, latch));
+ inflight.add(entry);
latch.await();
if (LOG.isTraceEnabled()) {
LOG.trace("Asynchronous callback received, will continue
routing exchangeId: {} -> {}",
@@ -124,10 +137,12 @@ public class DefaultAsyncProcessorAwaitManager extends
ServiceSupport implements
}
exchange.setException(e);
} finally {
- AwaitThread thread = inflight.remove(exchange);
+ // from here on the exchange is the caller's: an interrupt that
comes later leaves it alone
+ entry.finish();
+ boolean removed = inflight.remove(entry);
- if (statistics.isStatisticsEnabled() && thread != null) {
- long time = thread.getWaitDuration();
+ if (statistics.isStatisticsEnabled() && removed) {
+ long time = entry.getWaitDuration();
long total = totalDuration.get() + time;
totalDuration.set(total);
@@ -179,7 +194,7 @@ public class DefaultAsyncProcessorAwaitManager extends
ServiceSupport implements
@Override
public Collection<AwaitThread> browse() {
- return Collections.unmodifiableCollection(inflight.values());
+ return Collections.unmodifiableCollection(inflight);
}
@Override
@@ -199,36 +214,64 @@ public class DefaultAsyncProcessorAwaitManager extends
ServiceSupport implements
}
}
+ /**
+ * Releases the thread whose {@code process()} call started last for the
exchange. When a thread waits for the
+ * exchange while the exchange goes on, on another thread, through a step
that waits for it too (such as
+ * {@code ProducerTemplate.send(uri, exchange)}), only that inner thread
is released: it goes on with the failed
+ * exchange to the end of its route, and the callback then releases the
outer thread. So an interrupt never releases
+ * both threads of a nested wait (both would then route the exchange at
once). The stop of the manager releases
+ * every thread.
+ */
@Override
public void interrupt(Exchange exchange) {
- AwaitThreadEntry entry = (AwaitThreadEntry) inflight.get(exchange);
- if (entry != null) {
- try {
- StringBuilder sb = new StringBuilder(512);
- sb.append(
- "Interrupted while waiting for asynchronous callback,
will release the following blocked thread which was waiting for exchange to
finish processing with exchangeId: ");
- sb.append(exchange.getExchangeId());
- sb.append("\n");
-
- sb.append(dumpBlockedThread(entry));
-
- // dump a route stack trace of the exchange
- String routeStackTrace =
MessageHelper.dumpMessageHistoryStacktrace(exchange, exchangeFormatter, false);
- sb.append(routeStackTrace);
- LOG.warn(sb.toString());
+ AwaitThreadEntry innermost = null;
+ for (AwaitThreadEntry entry : inflight) {
+ if (entry.getExchange() == exchange && (innermost == null ||
entry.order > innermost.order)) {
+ innermost = entry;
+ }
+ }
+ if (innermost != null) {
+ interrupt(innermost);
+ }
+ }
- } catch (Exception e) {
- throw RuntimeCamelException.wrapRuntimeCamelException(e);
- } finally {
- if (statistics.isStatisticsEnabled()) {
- interruptedCounter.incrementAndGet();
- }
- exchange.setException(new RejectedExecutionException(
- "Interrupted while waiting for asynchronous callback
for exchangeId: " + exchange.getExchangeId()));
- exchange.getExchangeExtension().setInterrupted(true);
- entry.getLatch().countDown();
+ /**
+ * Releases the thread of the entry, unless it already returned. The WARN
line is built first, and an exception
+ * while building it is thrown only after the thread was released.
+ */
+ private void interrupt(AwaitThreadEntry entry) {
+ Exchange exchange = entry.getExchange();
+ String dump = null;
+ RuntimeException failure = null;
+ try {
+ StringBuilder sb = new StringBuilder(512);
+ sb.append(
+ "Interrupted while waiting for asynchronous callback, will
release the following blocked thread which was waiting for exchange to finish
processing with exchangeId: ");
+ sb.append(exchange.getExchangeId());
+ sb.append("\n");
+
+ sb.append(dumpBlockedThread(entry));
+
+ // dump a route stack trace of the exchange
+ String routeStackTrace =
MessageHelper.dumpMessageHistoryStacktrace(exchange, exchangeFormatter, false);
+ sb.append(routeStackTrace);
+ dump = sb.toString();
+ } catch (Exception e) {
+ failure = RuntimeCamelException.wrapRuntimeCamelException(e);
+ }
+ // the callback may have fired while the dump was made, and the
waiting thread may have returned the exchange
+ // to its caller as done: the exchange is then left alone
+ if (entry.interrupt()) {
+ if (statistics.isStatisticsEnabled()) {
+ interruptedCounter.incrementAndGet();
+ }
+ if (dump != null) {
+ LOG.warn(dump);
}
}
+ if (failure != null) {
+ throw failure;
+ }
}
@Override
@@ -262,7 +305,7 @@ public class DefaultAsyncProcessorAwaitManager extends
ServiceSupport implements
LOG.warn("The following threads are blocked and will be
interrupted so the threads are released:\n{}", sb);
for (AwaitThread entry : threads) {
try {
- interrupt(entry.getExchange());
+ interrupt((AwaitThreadEntry) entry);
} catch (Exception e) {
LOG.warn("Error while interrupting thread: {}. This
exception is ignored.",
entry.getBlockedThread().getName(),
@@ -275,8 +318,8 @@ public class DefaultAsyncProcessorAwaitManager extends
ServiceSupport implements
} else {
LOG.debug("Shutting down with no inflight threads.");
}
-
- inflight.clear();
+ // the entries are not cleared: each thread removes its own once it
returns, so a thread that is still blocked
+ // (not interrupted, or blocked since the threads were listed above)
stays listed, and can be interrupted
}
private static String dumpBlockedThread(AwaitThread entry) {
@@ -309,12 +352,17 @@ public class DefaultAsyncProcessorAwaitManager extends
ServiceSupport implements
private final Thread thread;
private final Exchange exchange;
private final CountDownLatch latch;
+ private final long order;
private final StopWatch watch = new StopWatch();
+ private final Lock lock = new ReentrantLock();
+ // guarded by lock: the waiting thread returned (finish), or interrupt
released it
+ private boolean finished;
- private AwaitThreadEntry(Thread thread, Exchange exchange,
CountDownLatch latch) {
+ private AwaitThreadEntry(Thread thread, Exchange exchange,
CountDownLatch latch, long order) {
this.thread = thread;
this.exchange = exchange;
this.latch = latch;
+ this.order = order;
}
@Override
@@ -351,6 +399,39 @@ public class DefaultAsyncProcessorAwaitManager extends
ServiceSupport implements
return latch;
}
+ /**
+ * Fails the exchange as interrupted and releases the waiting thread,
unless the callback already fired or the
+ * thread returned. The waiting thread sees the exception, as it
returns only after it called {@link #finish()}.
+ *
+ * @return whether the exchange was failed and the thread released
+ */
+ boolean interrupt() {
+ lock.lock();
+ try {
+ if (finished || latch.getCount() == 0) {
+ return false;
+ }
+ finished = true;
+ exchange.setException(new RejectedExecutionException(
+ "Interrupted while waiting for asynchronous callback
for exchangeId: " + exchange.getExchangeId()));
+ exchange.getExchangeExtension().setInterrupted(true);
+ latch.countDown();
+ return true;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /** Called by the waiting thread before it returns: an interrupt after
this leaves the exchange alone. */
+ void finish() {
+ lock.lock();
+ try {
+ finished = true;
+ } finally {
+ lock.unlock();
+ }
+ }
+
@Override
public String toString() {
return "AwaitThreadEntry[name=" + thread.getName() + ",
exchangeId=" + exchange.getExchangeId() + "]";
diff --git
a/core/camel-core/src/test/java/org/apache/camel/impl/DefaultAsyncProcessorAwaitManagerInterruptRaceTest.java
b/core/camel-core/src/test/java/org/apache/camel/impl/DefaultAsyncProcessorAwaitManagerInterruptRaceTest.java
new file mode 100644
index 000000000000..3ee9a1b4900c
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/impl/DefaultAsyncProcessorAwaitManagerInterruptRaceTest.java
@@ -0,0 +1,371 @@
+/*
+ * 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.lang.reflect.Proxy;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.RejectedExecutionException;
+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.Exchange;
+import org.apache.camel.impl.engine.DefaultAsyncProcessorAwaitManager;
+import org.apache.camel.spi.UnitOfWork;
+import org.apache.camel.support.AsyncProcessorSupport;
+import org.apache.camel.support.DefaultExchange;
+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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * An interrupt of the await manager (JMX, or the stop of the CamelContext)
races with the callback of the processor it
+ * waits for, and with other threads that wait for the same exchange.
+ */
+class DefaultAsyncProcessorAwaitManagerInterruptRaceTest {
+
+ // threads also start threads
+ private final List<Thread> threads = new CopyOnWriteArrayList<>();
+ private final List<ControlledProcessor> processors = new ArrayList<>();
+ private CamelContext context;
+ private DefaultAsyncProcessorAwaitManager manager;
+
+ @BeforeEach
+ void setUp() {
+ context = new DefaultCamelContext();
+ context.start();
+ manager = new DefaultAsyncProcessorAwaitManager();
+ manager.start();
+ }
+
+ @AfterEach
+ void tearDown() throws Exception {
+ // the callbacks that did not fire yet release the threads still
waiting
+ for (ControlledProcessor processor : processors) {
+ processor.complete();
+ }
+ for (Thread thread : threads) {
+ thread.join(TimeUnit.SECONDS.toMillis(10));
+ }
+ manager.stop();
+ context.stop();
+ }
+
+ @Test
+ void
interruptLeavesAnExchangeAloneWhoseCallbackFiredWhileItLoggedTheBlockedThread()
throws Exception {
+ Gate gate = new Gate();
+ Exchange exchange = gate.attach(new DefaultExchange(context));
+ ControlledProcessor processor = processor(null);
+ AtomicReference<Exception> exceptionAtReturn = new AtomicReference<>();
+ Thread waiter = thread("waiter", () -> {
+ manager.process(processor, exchange);
+ exceptionAtReturn.set(exchange.getException());
+ });
+ await().atMost(10, TimeUnit.SECONDS).until(() -> manager.size() == 1);
+
+ // the interrupt is making the WARN line of the blocked thread when
the callback fires
+ Thread interrupter = new Thread(() -> manager.interrupt(exchange),
"interrupter");
+ gate.gatedThread = interrupter;
+ interrupter.start();
+ assertTrue(gate.inside.await(10, TimeUnit.SECONDS), "the interrupt
reads the route of the blocked thread");
+ processor.complete();
+ waiter.join(TimeUnit.SECONDS.toMillis(10));
+ assertFalse(waiter.isAlive(), "the waiter returned once the callback
fired");
+ assertNull(exceptionAtReturn.get(), "the waiter returned the exchange
as done");
+
+ gate.proceed.countDown();
+ interrupter.join(TimeUnit.SECONDS.toMillis(10));
+ // on main the exchange that the caller already goes on with was
failed and marked interrupted
+ assertNull(exchange.getException());
+ assertFalse(exchange.getExchangeExtension().isInterrupted());
+ }
+
+ @Test
+ void twoThreadsWaitingForTheSameExchangeAreBothListed() throws Exception {
+ Exchange exchange = new DefaultExchange(context);
+ ControlledProcessor inner = processor(null);
+ AtomicReference<Thread> nested = new AtomicReference<>();
+ // the processor goes on with the exchange on another thread, which
calls a step that waits for it too (such as
+ // ProducerTemplate.send(uri, exchange))
+ ControlledProcessor outer = processor(() -> {
+ nested.set(Thread.currentThread());
+ await().atMost(10, TimeUnit.SECONDS).until(() -> manager.size() ==
1);
+ manager.process(inner, exchange);
+ });
+ Thread waiter = thread("waiter", () -> manager.process(outer,
exchange));
+ assertTrue(inner.called.await(10, TimeUnit.SECONDS));
+ await().atMost(10, TimeUnit.SECONDS).until(() -> waiter.getState() ==
Thread.State.WAITING
+ && nested.get().getState() == Thread.State.WAITING);
+
+ // on main the second thread replaced the entry of the first
+ assertEquals(2, manager.size(), "both blocked threads are listed");
+
+ inner.complete();
+ nested.get().join(TimeUnit.SECONDS.toMillis(10));
+ // on main the second thread removed the entry of the first when it
returned
+ assertEquals(1, manager.size(), "the thread still blocked stays
listed");
+ assertEquals(waiter,
manager.browse().iterator().next().getBlockedThread());
+
+ manager.interrupt(exchange);
+ waiter.join(TimeUnit.SECONDS.toMillis(10));
+ assertFalse(waiter.isAlive(), "the interrupt released the thread still
blocked");
+ assertInstanceOf(RejectedExecutionException.class,
exchange.getException());
+ assertEquals(0, manager.size());
+ }
+
+ @Test
+ void
interruptOfNestedWaitersReleasesTheInnerOneAndTheOuterOneThroughItsCallback()
throws Exception {
+ manager.getStatistics().setStatisticsEnabled(true);
+ Exchange exchange = new DefaultExchange(context);
+ Routing routing = new Routing();
+ ControlledProcessor inner = processor(null);
+ AtomicReference<Exception> innerException = new AtomicReference<>();
+ CountDownLatch innerReturned = new CountDownLatch(1);
+ CountDownLatch routeEnds = new CountDownLatch(1);
+ AtomicBoolean outerCallbackFired = new AtomicBoolean();
+ // the outer processor goes on with the exchange on another thread,
which calls a step that waits for it too
+ // (such as ProducerTemplate.send(uri, exchange)); when that step
returns, the route ends and fires the callback
+ // of the outer processor. The outer processor returns only once the
inner thread waits, so the outer thread is
+ // listed after the inner one: what counts is which call started
first, not which thread blocked first.
+ AsyncProcessorSupport outer = new AsyncProcessorSupport() {
+ @Override
+ public boolean process(Exchange ex, AsyncCallback callback) {
+ thread("route-worker", () -> {
+ manager.process(inner, ex);
+ routing.enter();
+ innerException.set(ex.getException());
+ innerReturned.countDown();
+ awaitLatch(routeEnds);
+ routing.leave();
+ outerCallbackFired.set(true);
+ callback.done(false);
+ });
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
manager.size() == 1);
+ return false;
+ }
+ };
+ AtomicBoolean outerReleasedByCallback = new AtomicBoolean();
+ AtomicReference<Exception> outerException = new AtomicReference<>();
+ Thread waiter = thread("waiter", () -> {
+ manager.process(outer, exchange);
+ routing.enter();
+ outerReleasedByCallback.set(outerCallbackFired.get());
+ outerException.set(exchange.getException());
+ routing.leave();
+ });
+ try {
+ await().atMost(10, TimeUnit.SECONDS).until(() -> manager.size() ==
2);
+
+ manager.interrupt(exchange);
+ // releasing every waiting thread fails here, and releasing the
thread that blocked last (the outer one)
+ // fails next
+ assertEquals(1, manager.getStatistics().getThreadsInterrupted(),
"only the inner thread is released");
+ assertTrue(innerReturned.await(10, TimeUnit.SECONDS), "the inner
thread was released");
+ assertInstanceOf(RejectedExecutionException.class,
innerException.get());
+ assertEquals(1, manager.size(), "the outer thread still waits");
+ assertEquals(waiter,
manager.browse().iterator().next().getBlockedThread());
+ } finally {
+ routeEnds.countDown();
+ }
+ waiter.join(TimeUnit.SECONDS.toMillis(10));
+ assertFalse(waiter.isAlive(), "the outer thread was released");
+ assertTrue(outerReleasedByCallback.get(), "the outer thread was
released by the callback of the route");
+ assertInstanceOf(RejectedExecutionException.class,
outerException.get());
+ assertEquals(1, routing.most.get(), "the interrupt did not release
both threads of the nested wait");
+ assertEquals(0, manager.size());
+ }
+
+ @Test
+ void threadThatWaitsWhileTheManagerStopsIsReleasedOrStaysListed() throws
Exception {
+ // the first exchange is in a bin of the map of main after the one of
the second, so the iteration of the stop
+ // that is at the first has passed the bin of the second
(DefaultExchange does not override hashCode). The bins
+ // only matter for the implementation of main, which kept the entries
in a map keyed by the exchange: with an
+ // entry per thread the test passes for any two exchanges.
+ Gate gate = new Gate();
+ Exchange first = new DefaultExchange(context);
+ while (bin(first) == 0) {
+ first = new DefaultExchange(context);
+ }
+ Exchange second = new DefaultExchange(context);
+ while (bin(second) >= bin(first)) {
+ second = new DefaultExchange(context);
+ }
+ gate.attach(first);
+ Exchange e1 = first;
+ Exchange e2 = second;
+ ControlledProcessor p1 = processor(null);
+ ControlledProcessor p2 = processor(null);
+ Thread w1 = thread("waiter-1", () -> manager.process(p1, e1));
+ await().atMost(10, TimeUnit.SECONDS).until(() -> manager.size() == 1);
+
+ Thread stopper = new Thread(manager::stop, "stopper");
+ gate.gatedThread = stopper;
+ stopper.start();
+ assertTrue(gate.inside.await(10, TimeUnit.SECONDS), "the stop
interrupts the first thread");
+ Thread w2 = thread("waiter-2", () -> manager.process(p2, e2));
+ await().atMost(10, TimeUnit.SECONDS).until(() -> w2.getState() ==
Thread.State.WAITING);
+ gate.proceed.countDown();
+ stopper.join(TimeUnit.SECONDS.toMillis(10));
+ w1.join(TimeUnit.SECONDS.toMillis(10));
+ assertFalse(w1.isAlive(), "the stop released the first thread");
+
+ // the second thread waits since the stop listed the threads: the stop
released it, or it is still listed, so
+ // that it can be interrupted (on main its entry was cleared and it
could no longer be found)
+ if (w2.isAlive()) {
+ assertEquals(1, manager.size(), "the thread still blocked stays
listed");
+ manager.interrupt(e2);
+ }
+ w2.join(TimeUnit.SECONDS.toMillis(10));
+ assertFalse(w2.isAlive(), "the second thread was released");
+ assertTrue(e2.getExchangeExtension().isInterrupted());
+ }
+
+ private ControlledProcessor processor(Runnable onProcess) {
+ ControlledProcessor processor = new ControlledProcessor(onProcess);
+ processors.add(processor);
+ return processor;
+ }
+
+ private Thread thread(String name, Runnable task) {
+ Thread thread = new Thread(task, name);
+ threads.add(thread);
+ thread.start();
+ return thread;
+ }
+
+ private static void awaitLatch(CountDownLatch latch) {
+ try {
+ latch.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ /** How many threads route the exchange at once, and the most seen. */
+ private static final class Routing {
+ final AtomicInteger now = new AtomicInteger();
+ final AtomicInteger most = new AtomicInteger();
+
+ void enter() {
+ most.accumulateAndGet(now.incrementAndGet(), Math::max);
+ }
+
+ void leave() {
+ now.decrementAndGet();
+ }
+ }
+
+ /** The bin of a key in a ConcurrentHashMap of 16 bins (the spread and
mask of ConcurrentHashMap). */
+ private static int bin(Object key) {
+ int h = key.hashCode();
+ return ((h ^ (h >>> 16)) & 0x7fffffff) & 15;
+ }
+
+ /**
+ * Parks a given thread when the await manager reads the route of the
exchange while it interrupts a blocked thread
+ * (the WARN line of the blocked thread has its route id), until the test
lets it go on.
+ */
+ private static final class Gate {
+ volatile Thread gatedThread;
+ final CountDownLatch inside = new CountDownLatch(1);
+ final CountDownLatch proceed = new CountDownLatch(1);
+
+ Exchange attach(Exchange exchange) {
+ UnitOfWork uow = (UnitOfWork)
Proxy.newProxyInstance(UnitOfWork.class.getClassLoader(),
+ new Class<?>[] { UnitOfWork.class }, (proxy, method, args)
-> {
+ String name = method.getName();
+ if ("getRoute".equals(name) && Thread.currentThread()
== gatedThread && calledFromInterrupt()) {
+ gatedThread = null;
+ inside.countDown();
+ proceed.await(10, TimeUnit.SECONDS);
+ }
+ if ("hashCode".equals(name)) {
+ return System.identityHashCode(proxy);
+ }
+ if ("equals".equals(name)) {
+ return proxy == args[0];
+ }
+ if ("toString".equals(name)) {
+ return "GateUnitOfWork";
+ }
+ Class<?> type = method.getReturnType();
+ if (type == boolean.class) {
+ return false;
+ } else if (type == int.class) {
+ return 0;
+ } else if (type == long.class) {
+ return 0L;
+ }
+ return null;
+ });
+ exchange.getExchangeExtension().setUnitOfWork(uow);
+ return exchange;
+ }
+
+ private static boolean calledFromInterrupt() {
+ return StackWalker.getInstance().walk(frames -> frames.anyMatch(
+ f ->
f.getClassName().equals(DefaultAsyncProcessorAwaitManager.class.getName())
+ && "interrupt".equals(f.getMethodName())));
+ }
+ }
+
+ /**
+ * An asynchronous processor whose callback the test fires, from another
thread, when it chooses. An inner class, so
+ * that the thread it starts in process() is tracked in threads and joined
by tearDown.
+ */
+ private final class ControlledProcessor extends AsyncProcessorSupport {
+ final AtomicReference<AsyncCallback> callback = new
AtomicReference<>();
+ final CountDownLatch called = new CountDownLatch(1);
+ private final Runnable onProcess;
+
+ ControlledProcessor(Runnable onProcess) {
+ this.onProcess = onProcess;
+ }
+
+ @Override
+ public boolean process(Exchange exchange, AsyncCallback callback) {
+ this.callback.set(callback);
+ called.countDown();
+ if (onProcess != null) {
+ thread("processor-worker", onProcess);
+ }
+ return false;
+ }
+
+ void complete() throws InterruptedException {
+ AsyncCallback cb = callback.getAndSet(null);
+ if (cb != null) {
+ Thread thread = new Thread(() -> cb.done(false),
"async-completer");
+ thread.start();
+ thread.join(TimeUnit.SECONDS.toMillis(10));
+ }
+ }
+ }
+}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/AbstractExchange.java
b/core/camel-support/src/main/java/org/apache/camel/support/AbstractExchange.java
index 9b4cd0d75a1f..89c524340d7d 100644
---
a/core/camel-support/src/main/java/org/apache/camel/support/AbstractExchange.java
+++
b/core/camel-support/src/main/java/org/apache/camel/support/AbstractExchange.java
@@ -90,6 +90,8 @@ abstract class AbstractExchange implements Exchange,
ExchangeExtension {
private boolean notifyEvent;
private boolean interruptable = true;
private boolean interrupted;
+ // calls of the await manager for this exchange (not reset, not copied)
+ private long awaitOrder;
private boolean routeStop;
private boolean rollbackOnly;
private boolean rollbackOnlyLast;
@@ -1062,6 +1064,11 @@ abstract class AbstractExchange implements Exchange,
ExchangeExtension {
}
}
+ @Override
+ public long nextAwaitOrder() {
+ return ++awaitOrder;
+ }
+
@Override
public <T> T getInOrNull(Class<T> type) {
if (in == null) {
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/ExtendedExchangeExtension.java
b/core/camel-support/src/main/java/org/apache/camel/support/ExtendedExchangeExtension.java
index 0b3442289386..d7f4ed81e053 100644
---
a/core/camel-support/src/main/java/org/apache/camel/support/ExtendedExchangeExtension.java
+++
b/core/camel-support/src/main/java/org/apache/camel/support/ExtendedExchangeExtension.java
@@ -51,6 +51,7 @@ public class ExtendedExchangeExtension implements
ExchangeExtension {
private boolean notifyEvent;
private boolean interruptable = true;
private boolean interrupted;
+ private long awaitOrder;
private boolean routeStop;
private boolean rollbackOnly;
private boolean rollbackOnlyLast;
@@ -306,6 +307,11 @@ public class ExtendedExchangeExtension implements
ExchangeExtension {
}
}
+ @Override
+ public long nextAwaitOrder() {
+ return ++awaitOrder;
+ }
+
@Override
public boolean isRollbackOnly() {
return rollbackOnly;
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index d92df4db2c6a..28a12b52fbbb 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -199,6 +199,24 @@ Starting in 4.24:
* The Cache EIP stores keys directly without a namespace prefix, preserving
documented cache invalidation recipes (`cache.delete(key)` and
`cache.clear()`). Note that because cache keys are un-prefixed, calling
`clear()` on a `KeyValueRepository` shared with the Cache EIP will clear all
entries in that repository, including state-store entries. It is recommended to
use a dedicated repository for the Cache EIP when co-located with state-store.
* `KeyValueAggregationRepository` safely verifies entry types before
unmarshalling, ignoring unexpected types gracefully instead of failing with a
class cast exception.
+=== camel-api - ExchangeExtension has a new method
+
+`org.apache.camel.ExchangeExtension`, the internal extension of an `Exchange`,
has a new method that an implementation
+must implement:
+
+[source,java]
+----
+long nextAwaitOrder()
+----
+
+It returns a number that grows with each call for the same exchange, which the
await manager uses to tell which of
+the threads that wait for the same exchange made its `process()` call last.
Camel's exchanges (`DefaultExchange`,
+`DefaultPooledExchange`) implement it; only a custom implementation of
`ExchangeExtension` needs a change.
+
+The await manager now keeps one entry per blocked thread, not one per
exchange. So `browse()` (JMX and the blocked
+console) lists one row per blocked thread, and can show two rows for one
exchange when two threads wait for it (for
+example a nested `ProducerTemplate` call that sends the same exchange).
+
=== camel-core - Idempotent Consumer processes an exchange that a calling
route redelivers
When the error handler of a calling route redelivers an exchange that failed
inside an Idempotent Consumer (for