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 1b9bfaf90693 CAMEL-26459: camel-disruptor - multipleConsumers: 
complete the exchange once when all consumers are done, as camel-seda (#30931)
1b9bfaf90693 is described below

commit 1b9bfaf9069339f4e31790e065fb06d74255c3c7
Author: Claus Ibsen <[email protected]>
AuthorDate: Fri Nov 27 20:30:38 2026 +0100

    CAMEL-26459: camel-disruptor - multipleConsumers: complete the exchange 
once when all consumers are done, as camel-seda (#30931)
    
    The first consumer that failed completed the exchange at once, while the 
other
    consumers were still routing it: the on completions of the caller (such as a
    file rollback) ran too early, and for InOut the reply set the ignore flag of
    the producer, so a consumer still busy with an earlier event skipped the
    message as if timed out. The first failure is now recorded and copied back
    when the last consumer is done, and the exchange completes once.
    
    Signed-off-by: Claus Ibsen <[email protected]>
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/catalog/docs/disruptor-component.adoc    |   3 +
 .../src/main/docs/disruptor-component.adoc         |   3 +
 .../MultipleConsumerSynchronizedExchange.java      |  29 +++---
 ...ptorMultipleConsumersInOutLateConsumerTest.java | 110 +++++++++++++++++++++
 ...DisruptorMultipleConsumersOnCompletionTest.java |  14 +--
 .../MultipleConsumerSynchronizedExchangeTest.java  |  32 ++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |  12 +++
 7 files changed, 183 insertions(+), 20 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/disruptor-component.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/disruptor-component.adoc
index a37af92e20cd..7cb3e3f4f965 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/disruptor-component.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/disruptor-component.adoc
@@ -271,6 +271,9 @@ spring beans.
 Since we have specified multipleConsumers=true on the Disruptor foo
 endpoint, we can have those two or more consumers receive their own copy
 of the message as a kind of _publish/subscriber_ style messaging.
+The message is completed once all consumers are done with it (as with SEDA): 
if a consumer fails, its failure is
+copied back to the message (the results of the consumers are not aggregated), 
so a producer waiting for the reply
+gets the failure, and the on completions of the caller run, only when all 
consumers are done.
 As the beans are part of a unit test, they simply send the message to a mock 
endpoint,
 but notice how we can use _@Consume_ to consume from the Disruptor.
 
diff --git a/components/camel-disruptor/src/main/docs/disruptor-component.adoc 
b/components/camel-disruptor/src/main/docs/disruptor-component.adoc
index a37af92e20cd..7cb3e3f4f965 100644
--- a/components/camel-disruptor/src/main/docs/disruptor-component.adoc
+++ b/components/camel-disruptor/src/main/docs/disruptor-component.adoc
@@ -271,6 +271,9 @@ spring beans.
 Since we have specified multipleConsumers=true on the Disruptor foo
 endpoint, we can have those two or more consumers receive their own copy
 of the message as a kind of _publish/subscriber_ style messaging.
+The message is completed once all consumers are done with it (as with SEDA): 
if a consumer fails, its failure is
+copied back to the message (the results of the consumers are not aggregated), 
so a producer waiting for the reply
+gets the failure, and the on completions of the caller run, only when all 
consumers are done.
 As the beans are part of a unit test, they simply send the message to a mock 
endpoint,
 but notice how we can use _@Consume_ to consume from the Disruptor.
 
diff --git 
a/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/MultipleConsumerSynchronizedExchange.java
 
b/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/MultipleConsumerSynchronizedExchange.java
index cc82c88247ad..1ce386e41727 100644
--- 
a/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/MultipleConsumerSynchronizedExchange.java
+++ 
b/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/MultipleConsumerSynchronizedExchange.java
@@ -18,6 +18,7 @@ package org.apache.camel.component.disruptor;
 
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
 
 import org.apache.camel.Exchange;
 import org.apache.camel.support.ExchangeHelper;
@@ -30,15 +31,16 @@ public class MultipleConsumerSynchronizedExchange extends 
AbstractSynchronizedEx
 
     private final int expectedConsumers;
 
-    // the consumers copy this one: the first consumer that fails copies its 
result into the exchange, which the other
-    // consumers must neither see nor read while it is written
+    // the consumers copy this one, so that none of them sees (or reads while 
it is written) the result of a failure,
+    // which is copied into the exchange when all consumers are done
     private final Exchange exchangeToCopy;
 
     private final AtomicInteger processedConsumers = new AtomicInteger();
 
     private final AtomicBoolean resultHandled = new AtomicBoolean();
 
-    private final AtomicBoolean failed = new AtomicBoolean();
+    // the result of the first consumer that failed, which is copied back when 
all consumers are done
+    private final AtomicReference<Exchange> failure = new AtomicReference<>();
 
     public MultipleConsumerSynchronizedExchange(Exchange exchange, int 
expectedConsumers) {
         super(exchange);
@@ -55,25 +57,24 @@ public class MultipleConsumerSynchronizedExchange extends 
AbstractSynchronizedEx
 
     @Override
     public void consumed(Exchange result) {
-        boolean failure = result.getException() != null;
-        if (failure) {
+        if (result.getException() != null) {
             // before this consumer is counted, so that the consumer that is 
counted last knows of the failure: this
             // write comes before our incrementAndGet in program order, and 
the last consumer's incrementAndGet on the
-            // same AtomicInteger happens after ours, so its failed.get() sees 
it
-            failed.set(true);
+            // same AtomicInteger happens after ours, so its failure.get() 
sees it
+            failure.compareAndSet(null, result);
         }
         int processed = processedConsumers.incrementAndGet();
 
-        // complete the exchange once: at the first failure (the consumers 
that are still routing then complete
-        // nothing), or when all consumers are done and none of them failed
-        if (failure) {
-            if (!resultHandled.getAndSet(true)) {
+        // complete the exchange once, when all consumers are done (as SEDA): 
completing it at the first failure would
+        // run the on completions of the caller (such as a rollback of the 
file consumer, or the reply of an InOut
+        // producer) while the other consumers are still routing it
+        if (processed == expectedConsumers && !resultHandled.getAndSet(true)) {
+            Exchange failed = failure.get();
+            if (failed != null) {
                 // only the result of a failure is copied back (as SEDA, whose 
multicast to its consumers has no
                 // aggregation strategy)
-                ExchangeHelper.copyResults(getExchange(), result);
-                performSynchronization();
+                ExchangeHelper.copyResults(getExchange(), failed);
             }
-        } else if (processed == expectedConsumers && !failed.get() && 
!resultHandled.getAndSet(true)) {
             performSynchronization();
         }
     }
diff --git 
a/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorMultipleConsumersInOutLateConsumerTest.java
 
b/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorMultipleConsumersInOutLateConsumerTest.java
new file mode 100644
index 000000000000..e368317458ac
--- /dev/null
+++ 
b/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorMultipleConsumersInOutLateConsumerTest.java
@@ -0,0 +1,110 @@
+/*
+ * 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.disruptor;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.builder.NotifyBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * An InOut producer gets the failure of a consumer only when all consumers 
are done, so a consumer that is still busy
+ * with an earlier exchange routes the exchange as well, instead of ignoring 
it as if the producer had timed out.
+ */
+public class DisruptorMultipleConsumersInOutLateConsumerTest extends 
CamelTestSupport {
+
+    private static final String URI = 
"disruptor:inOutLate?multipleConsumers=true";
+
+    private final CountDownLatch blockerStarted = new CountDownLatch(1);
+    private final CountDownLatch release = new CountDownLatch(1);
+
+    @AfterEach
+    void releaseConsumers() {
+        // do not leave a consumer waiting when a test fails
+        release.countDown();
+    }
+
+    @Test
+    void testLateConsumerRoutesTheRequestThatAnotherConsumerFailed() throws 
Exception {
+        MockEndpoint mock = getMockEndpoint("mock:late");
+        mock.expectedBodiesReceived("blocker", "fail");
+
+        NotifyBuilder failingDone = new 
NotifyBuilder(context).from("disruptor:inOutLate*").whenDone(2).create();
+
+        // the late consumer is busy with this one, so it gets to the request 
only when it is released
+        template.sendBody(URI, "blocker");
+        assertTrue(blockerStarted.await(10, TimeUnit.SECONDS), "The late 
consumer should be busy");
+
+        // the other consumer is done with both exchanges, and has failed the 
request
+        CompletableFuture<Object> future = template.asyncRequestBody(URI, 
"fail");
+        assertTrue(failingDone.matches(10, TimeUnit.SECONDS), "The failing 
consumer should be done");
+        // the producer waits for the late consumer as well
+        assertFalse(future.isDone(), "The producer should still wait for the 
late consumer");
+
+        release.countDown();
+
+        ExecutionException e = assertThrows(ExecutionException.class, () -> 
future.get(20, TimeUnit.SECONDS));
+        IllegalArgumentException cause = findCause(e, 
IllegalArgumentException.class);
+        assertNotNull(cause, "The failure of the consumer should be returned: 
" + e);
+        assertEquals("Forced", cause.getMessage());
+
+        MockEndpoint.assertIsSatisfied(context);
+    }
+
+    private static <T extends Throwable> T findCause(Throwable t, Class<T> 
type) {
+        for (Throwable cause = t; cause != null; cause = cause.getCause()) {
+            if (type.isInstance(cause)) {
+                return type.cast(cause);
+            }
+        }
+        return null;
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(URI).errorHandler(noErrorHandler())
+                        .filter(body().isEqualTo("fail"))
+                        .throwException(new 
IllegalArgumentException("Forced"));
+
+                from(URI).errorHandler(noErrorHandler())
+                        .filter(body().isEqualTo("blocker"))
+                        .process(e -> {
+                            blockerStarted.countDown();
+                            release.await(20, TimeUnit.SECONDS);
+                        })
+                        .end()
+                        .to("mock:late");
+            }
+        };
+    }
+}
diff --git 
a/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorMultipleConsumersOnCompletionTest.java
 
b/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorMultipleConsumersOnCompletionTest.java
index 2c599456e071..e0028bd3f26c 100644
--- 
a/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorMultipleConsumersOnCompletionTest.java
+++ 
b/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorMultipleConsumersOnCompletionTest.java
@@ -27,7 +27,6 @@ import org.apache.camel.builder.RouteBuilder;
 import org.apache.camel.component.mock.MockEndpoint;
 import org.apache.camel.support.SynchronizationAdapter;
 import org.apache.camel.test.junit6.CamelTestSupport;
-import org.awaitility.Awaitility;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.Test;
 
@@ -61,15 +60,16 @@ public class DisruptorMultipleConsumersOnCompletionTest 
extends CamelTestSupport
         MockEndpoint slow = getMockEndpoint("mock:slow");
         slow.expectedBodiesReceived("fail-first");
 
+        NotifyBuilder failureDone = new 
NotifyBuilder(context).from("disruptor:fanout*").whenDone(1).create();
         template.sendBody("direct:start", "fail-first");
 
-        // the consumer that fails completes the exchange, while the other 
consumer is still routing it
-        Awaitility.await().atMost(5, TimeUnit.SECONDS).until(() -> 
!events.isEmpty());
-        assertEquals(List.of("failure:fail-first"), events);
+        // the consumer that fails does not complete the exchange, while the 
other consumer is still routing it
+        assertTrue(failureDone.matches(10, TimeUnit.SECONDS), "The consumer 
that fails should be done");
+        assertTrue(events.isEmpty(), "Events: " + events);
 
         release.countDown();
         MockEndpoint.assertIsSatisfied(context);
-        // the other consumer is done as well, which must not run the on 
completions a second time
+        // the exchange is completed once, with the failure, when the other 
consumer is done as well
         assertNoMoreEvents(List.of("failure:fail-first"));
     }
 
@@ -78,9 +78,11 @@ public class DisruptorMultipleConsumersOnCompletionTest 
extends CamelTestSupport
         MockEndpoint slow = getMockEndpoint("mock:slow");
         slow.expectedBodiesReceived("both-fail");
 
+        NotifyBuilder firstDone = new 
NotifyBuilder(context).from("disruptor:fanout*").whenDone(1).create();
         template.sendBody("direct:start", "both-fail");
 
-        Awaitility.await().atMost(5, TimeUnit.SECONDS).until(() -> 
!events.isEmpty());
+        assertTrue(firstDone.matches(10, TimeUnit.SECONDS), "The first 
consumer that fails should be done");
+        assertTrue(events.isEmpty(), "Events: " + events);
         release.countDown();
         MockEndpoint.assertIsSatisfied(context);
         assertNoMoreEvents(List.of("failure:both-fail"));
diff --git 
a/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/MultipleConsumerSynchronizedExchangeTest.java
 
b/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/MultipleConsumerSynchronizedExchangeTest.java
index e8226495c483..5bb26e13746e 100644
--- 
a/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/MultipleConsumerSynchronizedExchangeTest.java
+++ 
b/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/MultipleConsumerSynchronizedExchangeTest.java
@@ -100,4 +100,36 @@ public class MultipleConsumerSynchronizedExchangeTest {
         assertEquals(List.of("failure"), events);
         assertTrue(published.isFailed());
     }
+
+    @Test
+    void testFailureThenSuccessCompletesOnceWhenAllAreDone() throws Exception {
+        Exchange published = new DefaultExchange(context);
+        published.getMessage().setBody("Hello");
+        published.getExchangeExtension().addOnCompletion(new 
SynchronizationAdapter() {
+            @Override
+            public void onComplete(Exchange exchange) {
+                events.add("complete");
+            }
+
+            @Override
+            public void onFailure(Exchange exchange) {
+                events.add("failure");
+            }
+        });
+        MultipleConsumerSynchronizedExchange synchronizedExchange = new 
MultipleConsumerSynchronizedExchange(published, 2);
+
+        Exchange failedResult = new DefaultExchange(context);
+        failedResult.setException(new IllegalArgumentException("Forced"));
+        synchronizedExchange.consumed(failedResult);
+
+        // the other consumer is still routing the exchange, so it is not 
completed yet
+        assertTrue(events.isEmpty(), "Events: " + events);
+        assertFalse(published.isFailed());
+
+        synchronizedExchange.consumed(new DefaultExchange(context));
+
+        assertEquals(List.of("failure"), events);
+        assertTrue(published.isFailed());
+        assertEquals("Forced", published.getException().getMessage());
+    }
 }
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 6dbf47081dab..09a6c90b323f 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
@@ -520,6 +520,18 @@ restart is gone. A class that extends `SedaConsumer` and 
overrides `doRun()` mus
 instead, and should keep the loop condition `isCurrentStart(start) && 
isRunAllowed()` of the default implementation.
 The new protected method `isCurrentStart(int start)` returns true while no 
later start of the consumer has happened.
 
+=== camel-disruptor - with multipleConsumers the exchange completes once all 
consumers are done
+
+With `multipleConsumers=true`, the exchange now completes once, when all 
consumers are done with it, as with
+`camel-seda`. Before, the first consumer that failed completed it at once, 
while the other consumers were still
+routing their copy. Only a failure is copied back (the first one), the results 
of the consumers are not aggregated.
+
+* An `InOut` producer gets the failure of a consumer only once the other 
consumers are done as well, so its `timeout`
+covers all consumers. Before, a consumer that was still busy with an earlier 
message could then skip the message, as
+if the producer had timed out.
+* The on completions of the caller, such as the move or rollback of a file 
consumer, run once all consumers are done,
+and no longer while other consumers are still routing the message.
+
 === camel-resilience4j - a call that times out before it starts is not started 
later
 
 In asynchronous mode (`asynchronous=true`) with a timeout, the 
`timeoutCancelRunningFuture` option (`true` by default)

Reply via email to