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 737c819df6aa CAMEL-27519: camel-disruptor - producers fail instead of 
waiting forever when the new Disruptor of a reconfiguration fails to start 
(#30820)
737c819df6aa is described below

commit 737c819df6aa2b30fe4db9f4bf94aaada094aa6e
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 13:30:18 2026 +0530

    CAMEL-27519: camel-disruptor - producers fail instead of waiting forever 
when the new Disruptor of a reconfiguration fails to start (#30820)
    
    Cause: reconfigure() marks the cleared reference as being reconfigured
    (null, true) and then starts the new Disruptor. When start() throws, for
    example because the executor rejects the event handlers, the finally block
    only unlocks: the mark stays set. DelayedExecutor also keeps the event
    processors it had not handed over yet.
    
    Effect: every producer of the queue waits in getCurrentDisruptor() forever,
    also one with a timeout (the timeout starts after the publish). The next
    start() hands the stale event processors to the executor too, where they
    take threads meant for the new ones.
    
    Fix: a failed start() sets the reference to (null, false), so producers fail
    at once with DisruptorNotStartedException as when nothing is started, drops
    the event processors still queued in DelayedExecutor, halts the ones already
    handed over, logs one WARN line and rethrows. Exchanges buffered from a
    queue without consumer stay buffered for the next successful start. This
    covers the three callers of start(): reconfigure(), addEndpoint() and the
    move of the event handlers in removeEndpoint().
    
    * CAMEL-27519: camel-disruptor - review follow-up: clearer log message on a 
failed start
    
    - DisruptorReference: the WARN logged when the new Disruptor fails to start 
says
      that the exchanges buffered before the failure are kept, so it does not 
read as
      if exchanges sent after it were buffered too (producers fail at once).
    
    Log message only.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../component/disruptor/DisruptorReference.java    |  27 +++-
 .../disruptor/DisruptorFailedReconfigureTest.java  | 140 +++++++++++++++++++++
 2 files changed, 166 insertions(+), 1 deletion(-)

diff --git 
a/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorReference.java
 
b/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorReference.java
index d371e680af55..529b903cc530 100644
--- 
a/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorReference.java
+++ 
b/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorReference.java
@@ -171,8 +171,29 @@ public class DisruptorReference {
 
     private void start() throws Exception {
         LOGGER.debug("Starting disruptor {}", this);
-        Disruptor<ExchangeEvent> newDisruptor = createDisruptor();
+        Disruptor<ExchangeEvent> newDisruptor = null;
+        try {
+            newDisruptor = createDisruptor();
+            startDisruptor(newDisruptor);
+        } catch (Exception | Error e) {
+            // the reference was cleared and marked as being reconfigured, so 
producers wait for the new Disruptor: mark
+            // it as not started instead, so they fail (as when no Disruptor 
was started) instead of waiting forever
+            disruptor.set(null, false);
+            // and do not run the event processors of this Disruptor later on 
the executor (the next start would
+            // hand them over with its own), nor keep running the ones already 
handed over
+            delayedExecutor.clear();
+            if (newDisruptor != null) {
+                newDisruptor.halt();
+            }
+            handlers = new LifecycleAwareExchangeEventHandler[0];
+            LOGGER.warn("Failed to start disruptor {}, producers fail until it 
is started again"
+                        + " ({} exchanges buffered before this failure are 
kept until then): {}",
+                    uri, temporaryExchangeBuffer.size(), e.toString());
+            throw e;
+        }
+    }
 
+    private void startDisruptor(Disruptor<ExchangeEvent> newDisruptor) throws 
Exception {
         newDisruptor.start();
 
         if (executor != null) {
@@ -567,5 +588,9 @@ public class DisruptorReference {
                 actualExecutor.execute(command);
             }
         }
+
+        public void clear() {
+            delayedCommands.clear();
+        }
     }
 }
diff --git 
a/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorFailedReconfigureTest.java
 
b/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorFailedReconfigureTest.java
new file mode 100644
index 000000000000..48409a2a652c
--- /dev/null
+++ 
b/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorFailedReconfigureTest.java
@@ -0,0 +1,140 @@
+/*
+ * 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.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.spi.ThreadPoolProfile;
+import org.apache.camel.support.DefaultThreadPoolFactory;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.apache.camel.util.ObjectHelper;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * When the new Disruptor of a reconfiguration fails to start (here the 
executor of the event handlers rejects them),
+ * producers must fail instead of waiting forever for it, and the disruptor 
must work again once it is started.
+ */
+class DisruptorFailedReconfigureTest extends CamelTestSupport {
+
+    private static final String URI = "disruptor:foo?multipleConsumers=true";
+
+    private volatile boolean rejecting;
+    private Thread producer;
+
+    @AfterEach
+    void stopRejecting() {
+        rejecting = false;
+        if (producer != null) {
+            producer.interrupt();
+        }
+    }
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext camelContext = super.createCamelContext();
+        camelContext.getExecutorServiceManager().setThreadPoolFactory(new 
RejectingThreadPoolFactory());
+        return camelContext;
+    }
+
+    @Test
+    void producersFailWhileTheDisruptorCannotBeStarted() throws Exception {
+        MockEndpoint a = getMockEndpoint("mock:a");
+        a.expectedBodiesReceived("before", "after");
+        template.sendBody(URI, "before");
+
+        // adding a second consumer reconfigures the disruptor, whose new 
event handlers are rejected by the executor
+        rejecting = true;
+        assertThrows(Exception.class, () -> context.addRoutes(new 
RouteBuilder() {
+            @Override
+            public void configure() {
+                from(URI).routeId("b").to("mock:b");
+            }
+        }));
+
+        // a request/reply producer with a timeout fails instead of waiting 
for the disruptor forever
+        AtomicReference<Exception> failure = new AtomicReference<>();
+        producer = new Thread(() -> {
+            try {
+                template.requestBody(URI + "&timeout=1000", "during");
+            } catch (Exception e) {
+                failure.set(e);
+            }
+        }, "producer");
+        producer.setDaemon(true);
+        producer.start();
+        await().atMost(20, TimeUnit.SECONDS).until(() -> !producer.isAlive());
+        assertFalse(producer.isAlive());
+        Exception producerFailure = failure.get();
+        assertNotNull(producerFailure, "the producer did not fail");
+        
assertNotNull(ObjectHelper.getException(DisruptorNotStartedException.class, 
producerFailure),
+                () -> "the producer did not fail with 
DisruptorNotStartedException: " + producerFailure);
+
+        // the executor accepts the event handlers again: restarting the route 
starts the disruptor again
+        rejecting = false;
+        context.getRouteController().stopRoute("a");
+        context.getRouteController().startRoute("a");
+        template.sendBody(URI, "after");
+
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(URI).routeId("a").to("mock:a");
+            }
+        };
+    }
+
+    /**
+     * Creates thread pools that reject new tasks while {@link #rejecting} is 
set, as a pool that was shut down does.
+     */
+    private final class RejectingThreadPoolFactory extends 
DefaultThreadPoolFactory {
+
+        @Override
+        public ExecutorService newThreadPool(ThreadPoolProfile profile, 
ThreadFactory factory) {
+            return new ThreadPoolExecutor(
+                    profile.getPoolSize(), profile.getMaxPoolSize(), 60, 
TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
+                    factory) {
+                @Override
+                public void execute(Runnable command) {
+                    if (rejecting) {
+                        throw new RejectedExecutionException("Rejected by the 
test");
+                    }
+                    super.execute(command);
+                }
+            };
+        }
+    }
+}

Reply via email to