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 b72225087f91 CAMEL-26473: camel-base-engine -
AsyncProcessorAwaitManager: create the latch only when the callback is still
pending (#28817)
b72225087f91 is described below
commit b72225087f91111f5aeccb673b545198168c6fa8
Author: Adriano Machado <[email protected]>
AuthorDate: Mon Nov 2 01:30:25 2026 -0500
CAMEL-26473: camel-base-engine - AsyncProcessorAwaitManager: create the
latch only when the callback is still pending (#28817)
…he latch only when the callback is still pending
process allocated a CountDownLatch on every synchronous over asynchronous
call, although the callback has usually fired when the processor returns,
as the reactive executor runs the work in the calling thread. The latch is
now created only when the callback has not fired yet, with an atomic
handshake for a callback that arrives at that moment.
_Claude Code on behalf of Adriano Machado (@ammachado)_
_This was generated by an AI agent and may contain inaccuracies.
Please verify before relying on it._
Co-authored-by: Claude Opus 5.5 <[email protected]>
---
.../engine/DefaultAsyncProcessorAwaitManager.java | 35 +++++-
...faultAsyncProcessorAwaitManagerProcessTest.java | 128 +++++++++++++++++++++
2 files changed, 159 insertions(+), 4 deletions(-)
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 e831514cb668..480b381c0b9a 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
@@ -23,7 +23,9 @@ 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 org.apache.camel.AsyncCallback;
import org.apache.camel.AsyncProcessor;
import org.apache.camel.Exchange;
import org.apache.camel.RuntimeCamelException;
@@ -41,6 +43,7 @@ import org.slf4j.LoggerFactory;
public class DefaultAsyncProcessorAwaitManager extends ServiceSupport
implements AsyncProcessorAwaitManager {
private static final Logger LOG =
LoggerFactory.getLogger(DefaultAsyncProcessorAwaitManager.class);
+ private static final CountDownLatch DONE = new CountDownLatch(0);
private final AsyncProcessorAwaitManager.Statistics statistics = new
UtilizationStatistics();
private final AtomicLong blockedCounter = new AtomicLong();
@@ -77,10 +80,14 @@ public class DefaultAsyncProcessorAwaitManager extends
ServiceSupport implements
*/
@Override
public void process(final AsyncProcessor processor, final Exchange
exchange) {
- CountDownLatch latch = new CountDownLatch(1);
- processor.process(exchange, doneSync -> countDown(exchange, latch));
- if (latch.getCount() > 0) {
- await(exchange, latch);
+ 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);
+ }
}
}
@@ -138,6 +145,26 @@ public class DefaultAsyncProcessorAwaitManager extends
ServiceSupport implements
}
}
+ /**
+ * The value is null until either the callback fires, which sets {@link
#DONE}, or the waiting thread gives it the
+ * latch to count down. Most calls complete without waiting, so this
avoids creating the latch for them.
+ */
+ private final class AwaitCallback extends AtomicReference<CountDownLatch>
implements AsyncCallback {
+ private final transient Exchange exchange;
+
+ private AwaitCallback(Exchange exchange) {
+ this.exchange = exchange;
+ }
+
+ @Override
+ public void done(boolean doneSync) {
+ CountDownLatch latch = getAndSet(DONE);
+ if (latch != null) {
+ countDown(exchange, latch);
+ }
+ }
+ }
+
public void countDown(Exchange exchange, CountDownLatch latch) {
if (LOG.isTraceEnabled()) {
LOG.trace("Asynchronous callback received for exchangeId: {}",
exchange.getExchangeId());
diff --git
a/core/camel-core/src/test/java/org/apache/camel/impl/DefaultAsyncProcessorAwaitManagerProcessTest.java
b/core/camel-core/src/test/java/org/apache/camel/impl/DefaultAsyncProcessorAwaitManagerProcessTest.java
new file mode 100644
index 000000000000..5e9e4f7a1528
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/impl/DefaultAsyncProcessorAwaitManagerProcessTest.java
@@ -0,0 +1,128 @@
+/*
+ * 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.time.Duration;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.BiConsumer;
+
+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.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.assertTimeoutPreemptively;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The callback can fire before the processor returns, which is the common
case, or at any later time from another
+ * thread. In all cases process must return, and only after the callback fired.
+ */
+public class DefaultAsyncProcessorAwaitManagerProcessTest {
+
+ private static final Duration TIMEOUT = Duration.ofSeconds(30);
+
+ private final DefaultAsyncProcessorAwaitManager manager = new
DefaultAsyncProcessorAwaitManager();
+ private final ExecutorService otherThread =
Executors.newSingleThreadExecutor();
+ private CamelContext context;
+
+ @BeforeEach
+ public void startContext() {
+ context = new DefaultCamelContext();
+ context.start();
+ }
+
+ @AfterEach
+ public void stopContext() {
+ otherThread.shutdownNow();
+ context.stop();
+ }
+
+ @Test
+ public void testCallbackFiredBeforeProcessorReturnsDoesNotBlock() {
+ assertTimeoutPreemptively(TIMEOUT, () -> process((exchange, callback)
-> callback.done(true)));
+
+ assertEquals(0, manager.size());
+ }
+
+ @Test
+ public void testCallbackFiredTwiceDoesNotFail() {
+ assertTimeoutPreemptively(TIMEOUT, () -> process((exchange, callback)
-> {
+ callback.done(true);
+ callback.done(true);
+ }));
+
+ assertEquals(0, manager.size());
+ }
+
+ @Test
+ public void testBlocksUntilCallbackFiredFromAnotherThread() {
+ AtomicBoolean fired = new AtomicBoolean();
+
+ assertTimeoutPreemptively(TIMEOUT, () -> process((exchange, callback)
-> otherThread.execute(() -> {
+ // the waiting thread is listed as blocked, which proves process
did not return early
+ await().atMost(10, TimeUnit.SECONDS).until(() -> manager.size() ==
1);
+ fired.set(true);
+ callback.done(false);
+ })));
+
+ assertTrue(fired.get(), "process must not return before the callback
fired");
+ assertEquals(0, manager.size());
+ }
+
+ @Test
+ public void testCallbackRacingWithProcessorReturnIsNotLost() {
+ // a callback lost in the moment the latch is created would block
process forever
+ assertTimeoutPreemptively(TIMEOUT, () -> {
+ for (int i = 0; i < 20_000; i++) {
+ CountDownLatch returning = new CountDownLatch(1);
+ process((exchange, callback) -> {
+ otherThread.execute(() -> {
+ try {
+ returning.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ callback.done(false);
+ });
+ returning.countDown();
+ });
+ }
+ });
+ }
+
+ private void process(BiConsumer<Exchange, AsyncCallback> body) {
+ manager.process(new AsyncProcessorSupport() {
+ @Override
+ public boolean process(Exchange exchange, AsyncCallback callback) {
+ body.accept(exchange, callback);
+ return false;
+ }
+ }, new DefaultExchange(context));
+ }
+}