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 78d076d00b60 CAMEL-27528: camel-disruptor - a thread interrupted while 
it waits for the event handlers to start or stop no longer loops forever 
(#30822)
78d076d00b60 is described below

commit 78d076d00b60c93aacea6ea48c6ae94ec8bde27f
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 13:30:32 2026 +0530

    CAMEL-27528: camel-disruptor - a thread interrupted while it waits for the 
event handlers to start or stop no longer loops forever (#30822)
    
    Cause: start() and shutdownDisruptor() wait for each event handler with
    awaitStarted/awaitStopped (10 s), in a loop that catches
    InterruptedException, logs "Interrupted while waiting for the startup
    (shutdown) to complete" at INFO, sets the interrupt flag again and waits
    again. CountDownLatch.await() throws at once while the flag is set.
    
    Effect: once the thread is interrupted while an event handler has not
    started (or not stopped) yet, it spins at full CPU and logs one INFO line
    per iteration, until the event handler starts (stops), or forever if it
    never does, with the lock of the disruptor held. A test run on main wrote
    about 2 GB of log in a minute this way.
    
    Fix: both waits share one method, which never waits again with the flag
    set (the wait that throws clears it) and sets the flag again at the end,
    with one WARN line. An interrupt does not end the wait for the start: it
    goes on, without interruption, for the rest of the 10 s limit (main's
    loop had no limit, and spun). Producers use the new Disruptor once
    start() returns, and LMAX Disruptor.shutdown() only waits for the event
    processors that run, so returning before they run would let the next
    reconfiguration halt a ring buffer that holds accepted exchanges, which
    are then never processed. An interrupt ends the wait for the stop:
    Disruptor.shutdown() returned only once the running event processors had
    taken and handled every exchange published on the ring buffer, so an
    event handler that has not stopped is only shutting down, as after the
    10 s limit.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../component/disruptor/DisruptorReference.java    | 102 +++++----
 .../disruptor/DisruptorInterruptedWaitTest.java    | 239 +++++++++++++++++++++
 2 files changed, 300 insertions(+), 41 deletions(-)

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 529b903cc530..fc79982e2220 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
@@ -202,26 +202,10 @@ public class DisruptorReference {
         }
 
         //make sure all event handlers are correctly started before we continue
-        for (final LifecycleAwareExchangeEventHandler handler : handlers) {
-            boolean eventHandlerStarted = false;
-            while (!eventHandlerStarted) {
-                try {
-                    //The disruptor start command executed above should have 
triggered a start signal to all
-                    //event processors which, in their death, should notify 
our event handlers. They respond by
-                    //switching a latch and we want to await that latch here 
to make sure they are started.
-                    if (!handler.awaitStarted(10, TimeUnit.SECONDS)) {
-                        //we wait for a relatively long, but limited amount of 
time to prevent an application using
-                        //this component from hanging indefinitely
-                        //Please report a bug if you can reproduce this
-                        LOGGER.error("Disruptor/event handler failed to start 
properly, PLEASE REPORT");
-                    }
-                    eventHandlerStarted = true;
-                } catch (InterruptedException e) {
-                    LOGGER.info("Interrupted while waiting for the startup to 
complete");
-                    Thread.currentThread().interrupt();
-                }
-            }
-        }
+        //The disruptor start command executed above should have triggered a 
start signal to all
+        //event processors which, in their death, should notify our event 
handlers. They respond by
+        //switching a latch and we want to await that latch here to make sure 
they are started.
+        awaitEventHandlers(handlers, true);
 
         publishBufferedExchanges(newDisruptor);
 
@@ -366,27 +350,8 @@ public class DisruptorReference {
 
                 //they have already been given a trigger to halt when they are 
done by shutting down the disruptor
                 //we do however want to await their completion before they are 
scheduled to process events from the new
-                for (final LifecycleAwareExchangeEventHandler eventHandler : 
handlers) {
-                    boolean eventHandlerFinished = false;
-                    //the disruptor is now empty and all consumers are either 
done or busy processing their last exchange
-                    while (!eventHandlerFinished) {
-                        try {
-                            //The disruptor shutdown command executed above 
should have triggered a halt signal to all
-                            //event processors which, in their death, should 
notify our event handlers. They respond by
-                            //switching a latch and we want to await that 
latch here to make sure they are done.
-                            if (!eventHandler.awaitStopped(10, 
TimeUnit.SECONDS)) {
-                                //we wait for a relatively long, but limited 
amount of time to prevent an application using
-                                //this component from hanging indefinitely
-                                //Please report a bug if you can repruduce this
-                                LOGGER.error("Disruptor/event handler failed 
to shut down properly, PLEASE REPORT");
-                            }
-                            eventHandlerFinished = true;
-                        } catch (InterruptedException e) {
-                            LOGGER.info("Interrupted while waiting for the 
shutdown to complete");
-                            Thread.currentThread().interrupt();
-                        }
-                    }
-                }
+                //(the event processors, in their death, notify our event 
handlers, which switch a latch we await here)
+                awaitEventHandlers(handlers, false);
 
                 handlers = new LifecycleAwareExchangeEventHandler[0];
             }
@@ -395,6 +360,61 @@ public class DisruptorReference {
         }
     }
 
+    /**
+     * Waits until each of the event handlers has started (or stopped), for at 
most 10 seconds each. The interrupt flag
+     * is kept for the caller, and an interrupt never makes this wait again in 
a loop (the wait clears the flag when it
+     * throws).
+     * <p/>
+     * An interrupt does not end the wait for the start: producers use the new 
Disruptor once the start returns, and the
+     * next shutdown of a Disruptor (LMAX) only waits for the event processors 
that run, so a Disruptor whose event
+     * processors have not run yet would be halted with the exchanges 
published on it. The wait goes on for the rest of
+     * the time limit, and the flag is set again at the end. An interrupt ends 
the wait for the stop:
+     * {@link Disruptor#shutdown()} returned only once the event processors 
had taken every exchange published on the
+     * ring buffer and had handled it, so an event handler that has not 
stopped yet is only shutting down, as after the
+     * time limit.
+     */
+    static void awaitEventHandlers(final LifecycleAwareExchangeEventHandler[] 
eventHandlers, final boolean start) {
+        boolean interrupted = false;
+        try {
+            for (final LifecycleAwareExchangeEventHandler eventHandler : 
eventHandlers) {
+                final long deadline = System.nanoTime() + 
TimeUnit.SECONDS.toNanos(10);
+                boolean waiting = true;
+                while (waiting) {
+                    try {
+                        final long remaining = deadline - System.nanoTime();
+                        final boolean done = start
+                                ? eventHandler.awaitStarted(remaining, 
TimeUnit.NANOSECONDS)
+                                : eventHandler.awaitStopped(remaining, 
TimeUnit.NANOSECONDS);
+                        if (!done) {
+                            //we wait for a relatively long, but limited 
amount of time to prevent an application using
+                            //this component from hanging indefinitely
+                            //Please report a bug if you can reproduce this
+                            LOGGER.error("Disruptor/event handler failed to {} 
properly, PLEASE REPORT",
+                                    start ? "start" : "shut down");
+                        }
+                        waiting = false;
+                    } catch (InterruptedException e) {
+                        if (!start) {
+                            LOGGER.warn("Interrupted while waiting for the 
shutdown of the event handlers of a disruptor"
+                                        + " to complete, not waiting for them 
any longer");
+                            interrupted = true;
+                            return;
+                        }
+                        if (!interrupted) {
+                            LOGGER.warn("Interrupted while waiting for the 
startup of the event handlers of a disruptor"
+                                        + " to complete, still waiting for 
them before the disruptor is used");
+                        }
+                        interrupted = true;
+                    }
+                }
+            }
+        } finally {
+            if (interrupted) {
+                Thread.currentThread().interrupt();
+            }
+        }
+    }
+
     private void shutdownExecutor() {
         lock.lock();
         try {
diff --git 
a/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorInterruptedWaitTest.java
 
b/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorInterruptedWaitTest.java
new file mode 100644
index 000000000000..8d77f9d13dee
--- /dev/null
+++ 
b/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorInterruptedWaitTest.java
@@ -0,0 +1,239 @@
+/*
+ * 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.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.ThreadPoolExecutor;
+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.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.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.Logger;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.config.Property;
+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.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A thread that is interrupted while it waits for the event handlers of a 
disruptor to start or to stop must not wait
+ * again in a loop (each wait throws at once while the flag is set), which 
never ends and logs a line per iteration: it
+ * keeps its interrupt flag and logs once. The wait for the start goes on 
until the event handlers run, as the disruptor
+ * must not be used before; the wait for the stop ends.
+ */
+class DisruptorInterruptedWaitTest extends CamelTestSupport {
+
+    private static final String URI = "disruptor:foo";
+
+    private final List<Runnable> heldTasks = new ArrayList<>();
+    private volatile boolean holding;
+    private final AtomicInteger interruptedLogLines = new AtomicInteger();
+    private AbstractAppender appender;
+    private Thread waiting;
+
+    @BeforeEach
+    void captureLog() {
+        // counts the log lines of DisruptorReference, which do not go to the 
log file meanwhile: if the wait loops, it
+        // logs a line per iteration
+        appender = new AbstractAppender("interrupted-wait", null, null, true, 
Property.EMPTY_ARRAY) {
+            @Override
+            public void append(LogEvent event) {
+                if 
(event.getMessage().getFormattedMessage().startsWith("Interrupted while 
waiting")) {
+                    interruptedLogLines.incrementAndGet();
+                }
+            }
+        };
+        appender.start();
+        Logger logger = (Logger) 
LogManager.getLogger(DisruptorReference.class);
+        logger.addAppender(appender);
+        logger.setAdditive(false);
+    }
+
+    @AfterEach
+    void releaseAndRestoreLog() {
+        // event handlers that were held start now, which also ends a wait for 
them that loops
+        releaseHeldTasks();
+        if (waiting != null) {
+            await().atMost(20, TimeUnit.SECONDS).until(() -> 
!waiting.isAlive());
+        }
+        Logger logger = (Logger) 
LogManager.getLogger(DisruptorReference.class);
+        logger.removeAppender(appender);
+        logger.setAdditive(true);
+        appender.stop();
+    }
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext camelContext = super.createCamelContext();
+        camelContext.getExecutorServiceManager().setThreadPoolFactory(new 
HoldingThreadPoolFactory());
+        return camelContext;
+    }
+
+    @Test
+    void interruptedStartWaitsForTheEventHandlersBeforeTheDisruptorIsUsed() 
throws Exception {
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        mock.expectedBodiesReceived("m0", "m1", "m2", "m3", "m4");
+        DisruptorReference reference = context.getEndpoint(URI, 
DisruptorEndpoint.class).getDisruptor();
+
+        // the executor keeps the event processors of the next Disruptor 
without running them, so its event handler
+        // does not start yet; the thread that reconfigures the disruptor is 
interrupted, then sends 5 exchanges and
+        // reconfigures the disruptor again (not interrupted). The next 
shutdown only waits for the event processors that
+        // run: had the interrupted start returned before its event processor 
ran, that shutdown would halt the ring
+        // buffer with the 5 exchanges on it, and they would never be processed
+        holding = true;
+        AtomicReference<Exception> failure = new AtomicReference<>();
+        AtomicBoolean interruptedAfterwards = new AtomicBoolean();
+        waiting = new Thread(() -> {
+            try {
+                Thread.currentThread().interrupt();
+                reference.reconfigure();
+                interruptedAfterwards.set(Thread.interrupted());
+                for (int i = 0; i < 5; i++) {
+                    template.sendBody(URI, "m" + i);
+                }
+                reference.reconfigure();
+            } catch (Exception e) {
+                failure.set(e);
+            }
+        }, "interrupted-reconfiguration");
+        waiting.setDaemon(true);
+        waiting.start();
+
+        // the interrupted start waits for the event handler that does not 
start yet, without looping: it logs at most
+        // once for the shutdown of the old event handler and once for the 
start of the new one
+        await().atMost(5, TimeUnit.SECONDS)
+                .until(() -> heldTaskCount() > 0 && waiting.getState() == 
Thread.State.TIMED_WAITING);
+        assertTrue(interruptedLogLines.get() <= 2, "logged " + 
interruptedLogLines.get() + " times");
+
+        // once the executor runs the event processors, the start ends with 
the interrupt flag kept, and every exchange
+        // sent afterwards is processed
+        releaseHeldTasks();
+        await().atMost(20, TimeUnit.SECONDS).until(() -> !waiting.isAlive());
+        assertFalse(waiting.isAlive(), "the reconfiguration still waits for 
the event handler");
+        assertNull(failure.get());
+        assertTrue(interruptedAfterwards.get(), "the interrupt flag was not 
kept");
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+    }
+
+    @Test
+    void interruptedWaitForEventHandlersThatDoNotStopEnds() {
+        // event handlers that have started and do not stop (as a consumer 
busy past the time limit)
+        LifecycleAwareExchangeEventHandler first = startedEventHandler();
+        LifecycleAwareExchangeEventHandler second = startedEventHandler();
+        AtomicBoolean interruptedAfterwards = new AtomicBoolean();
+        waiting = new Thread(() -> {
+            Thread.currentThread().interrupt();
+            DisruptorReference.awaitEventHandlers(new 
LifecycleAwareExchangeEventHandler[] { first, second }, false);
+            interruptedAfterwards.set(Thread.currentThread().isInterrupted());
+        }, "interrupted-shutdown");
+        waiting.setDaemon(true);
+        waiting.start();
+
+        try {
+            await().atMost(5, TimeUnit.SECONDS).until(() -> 
!waiting.isAlive());
+            assertFalse(waiting.isAlive(), "the interrupted shutdown still 
waits for the event handlers");
+            assertTrue(interruptedAfterwards.get(), "the interrupt flag was 
not kept");
+            assertEquals(1, interruptedLogLines.get());
+        } finally {
+            // a wait that loops ends only once they stop: stop them before 
the log appender is removed
+            first.onShutdown();
+            second.onShutdown();
+        }
+    }
+
+    private static LifecycleAwareExchangeEventHandler startedEventHandler() {
+        LifecycleAwareExchangeEventHandler eventHandler = new 
AbstractLifecycleAwareExchangeEventHandler() {
+            @Override
+            public void onEvent(ExchangeEvent event, long sequence, boolean 
endOfBatch) {
+                // not used
+            }
+        };
+        eventHandler.onStart();
+        return eventHandler;
+    }
+
+    private int heldTaskCount() {
+        synchronized (heldTasks) {
+            return heldTasks.size();
+        }
+    }
+
+    private void releaseHeldTasks() {
+        List<Runnable> tasks;
+        synchronized (heldTasks) {
+            holding = false;
+            tasks = new ArrayList<>(heldTasks);
+            heldTasks.clear();
+        }
+        for (Runnable task : tasks) {
+            task.run();
+        }
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(URI).to("mock:result");
+            }
+        };
+    }
+
+    /**
+     * Creates thread pools that keep the tasks they get while {@link 
#holding} is set, without running them.
+     */
+    private final class HoldingThreadPoolFactory 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) {
+                    synchronized (heldTasks) {
+                        if (holding) {
+                            heldTasks.add(() -> super.execute(command));
+                            return;
+                        }
+                    }
+                    super.execute(command);
+                }
+            };
+        }
+    }
+}

Reply via email to