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 1a30ae57c0cd CAMEL-27527: camel-disruptor - do not lose the messages 
of producers that publish while a consumer is added or removed (#30821)
1a30ae57c0cd is described below

commit 1a30ae57c0cd729cc9dc0032064726df2976ec24
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 14:41:21 2026 +0530

    CAMEL-27527: camel-disruptor - do not lose the messages of producers that 
publish while a consumer is added or removed (#30821)
    
    Cause: a reconfiguration (a consumer starts, stops, is suspended or
    resumed) clears the reference to the Disruptor, drains and halts the old
    Disruptor and starts a new one. A producer reads the reference, then claims
    and publishes a slot on its ring buffer, and nothing made the
    reconfiguration wait for a producer that read the reference just before it
    was cleared. Producers that wait for a free slot on a full ring buffer
    (blockWhenFull, the default) have read it already.
    
    Effect: such a producer publishes on the old ring buffer after its event
    handlers were halted. An InOnly exchange is accepted and never processed,
    an InOut producer without timeout waits forever, and once the halted ring
    buffer is full the next ones wait in RingBuffer.next() forever. For a queue
    without consumer, the backlog that the first consumer gets goes through a
    buffer bounded to the queue size whose offer() result was ignored, so the
    exchanges of the producers that waited on the full ring buffer were dropped.
    
    Fix: producers are counted from reading the reference until they have
    published on its ring buffer (or failed to). shutdownDisruptor clears the
    reference, unblocks the blocking event handler, waits until the count is 0,
    and only then drains and halts the old Disruptor, so their exchanges are
    drained. A producer waiting for a free slot is counted too: the old event
    handlers keep running until the drain and free its slot. The buffer of the
    backlog of a queue without consumer has no bound. start() publishes what
    fits the new ring buffer before the reference is set, which does not wait;
    the rest is published, in the order of the backlog, by a separate thread,
    as a counted producer that holds no lock, so the thread that starts a route
    does not wait for its consumers while it holds the locks of the disruptor,
    the endpoint and the route start. If that thread cannot be started (any
    Throwable, such as OutOfMemoryError "unable to create native thread"), the
    rest stays buffered for the next start, and a VirtualMachineError is
    thrown again. A Disruptor without consumer keeps the backlog buffered for
    the first consumer.
    
    Ordering: the backlog keeps its own order, but the order of one producer is
    not kept across the hand-over. A producer that waited on the full ring
    buffer when the first consumer starts returns once its exchange is in the
    backlog, and its next sends can overtake that exchange (main lost that
    exchange instead). The same happens on each suspend and resume of the only
    consumer: with several producers, the exchanges of one producer can arrive
    out of order (main lost exchanges there).
    
    * CAMEL-27527: camel-disruptor - review follow-up: the wait for the 
producers in flight does not keep a core busy
    
    - awaitPublishesInFlight(): the pause between two checks doubles from 1 
microsecond up to 1 ms. A pause of 1
      microsecond took a full core for as long as a producer waited for a free 
slot (500 ms of CPU in 500 ms of waiting,
      measured on macOS), and Thread.onSpinWait() would not change that. On an 
interrupted thread (such as a CamelContext
      stop that timed out) parkNanos returns at once, so the flag is cleared 
for the wait and set again after it.
    - New tests aReconfigurationWaitsForTheProducersWithoutSpinning and
      aReconfigurationOnAnInterruptedThreadWaitsForTheProducersWithoutSpinning: 
the CPU time of the reconfiguration thread
      while it waits half a second for the producers is under half of it, and 
the interrupt flag is kept. Both fail
      without this change (497 and 501 ms of CPU in 505 ms).
    - DisruptorReconfigureWithWaitingProducersTest: the backlog thread is 
matched by the name of the test's CamelContext
      too, so a thread of another disruptor test in the same JVM does not 
match; the comment of
      restOfTheBacklogStaysBufferedWhenItsThreadCannotBeStarted says that the 
test throws an Error that is not a
      VirtualMachineError (an OutOfMemoryError is thrown again).
    - Component docs: while a Disruptor has no consumer, a reconfiguration 
keeps the pending exchanges buffered for the
      first consumer, so the queue can hold more than size exchanges; 
getRemainingCapacity() does not count the buffered
      ones, getPendingExchangeCount() does.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/catalog/docs/disruptor-component.adoc    |   5 +
 .../src/main/docs/disruptor-component.adoc         |   5 +
 .../component/disruptor/DisruptorReference.java    | 204 +++++++++-
 ...sruptorReconfigureWithWaitingProducersTest.java | 446 +++++++++++++++++++++
 4 files changed, 642 insertions(+), 18 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 4fb1d1e7c904..a37af92e20cd 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
@@ -42,6 +42,11 @@ retrieved, only the number of exchanges.
 * The Disruptor requires its consumers (multicasted or otherwise) to be
 statically configured. Adding or removing consumers on the fly requires
 complete flushing of all pending exchanges in the Disruptor.
+* While a Disruptor has no consumer, a reconfiguration (for example when
+its endpoint is added again) keeps the pending exchanges in a buffer for
+the first consumer. The queue can then hold more than `size` exchanges:
+`getRemainingCapacity()` does not count the buffered ones, and
+`getPendingExchangeCount()` does.
 * As a result of the reconfiguration: Data sent over a Disruptor is
 directly processed and 'gone' if there is at least one consumer, late
 joiners only get new exchanges published after they've joined.
diff --git a/components/camel-disruptor/src/main/docs/disruptor-component.adoc 
b/components/camel-disruptor/src/main/docs/disruptor-component.adoc
index 4fb1d1e7c904..a37af92e20cd 100644
--- a/components/camel-disruptor/src/main/docs/disruptor-component.adoc
+++ b/components/camel-disruptor/src/main/docs/disruptor-component.adoc
@@ -42,6 +42,11 @@ retrieved, only the number of exchanges.
 * The Disruptor requires its consumers (multicasted or otherwise) to be
 statically configured. Adding or removing consumers on the fly requires
 complete flushing of all pending exchanges in the Disruptor.
+* While a Disruptor has no consumer, a reconfiguration (for example when
+its endpoint is added again) keeps the pending exchanges in a buffer for
+the first consumer. The queue can then hold more than `size` exchanges:
+`getRemainingCapacity()` does not count the buffered ones, and
+`getPendingExchangeCount()` does.
 * As a result of the reconfiguration: Data sent over a Disruptor is
 directly processed and 'gone' if there is at least one consumer, late
 joiners only get new exchanges published after they've joined.
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 fc79982e2220..d8dc117c1cc4 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
@@ -20,17 +20,17 @@ import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.LinkedList;
-import java.util.List;
 import java.util.Map;
 import java.util.Queue;
 import java.util.Set;
 import java.util.WeakHashMap;
-import java.util.concurrent.ArrayBlockingQueue;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executor;
 import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
 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.AtomicMarkableReference;
 import java.util.concurrent.locks.Lock;
@@ -77,9 +77,23 @@ public class DisruptorReference {
 
     private final DisruptorWaitStrategy waitStrategy;
 
-    private final Queue<Exchange> temporaryExchangeBuffer;
+    // the exchanges taken from the ring buffer of a Disruptor without 
consumer when it is shut down, for the next
+    // Disruptor: not bounded, as the producers that waited on its full ring 
buffer publish on it before it is shut down
+    private final Queue<Exchange> temporaryExchangeBuffer = new 
LinkedBlockingQueue<>();
     private final Lock lock = new ReentrantLock();
 
+    // the producers that have read the current Disruptor and not yet 
published on its ring buffer (or failed to): a
+    // reconfiguration clears the reference, then waits for them before it 
drains and halts the Disruptor, so that no
+    // exchange is published on a ring buffer whose event handlers have been 
halted
+    private static final long MAX_PUBLISHES_IN_FLIGHT_PAUSE = 
TimeUnit.MILLISECONDS.toNanos(1);
+
+    private final AtomicInteger publishesInFlight = new AtomicInteger();
+
+    // the current Disruptor while it has consumers (the buffered exchanges 
are only published on such a Disruptor), and
+    // whether a thread publishes the buffered exchanges that did not fit its 
ring buffer when it was started
+    private volatile Disruptor<ExchangeEvent> consumingDisruptor;
+    private final AtomicBoolean publishingBufferedExchanges = new 
AtomicBoolean();
+
     //access guarded by this
     private ExecutorService executor;
     // the CamelContext whose ExecutorServiceManager created the executor, 
which shuts it down when it stops
@@ -102,7 +116,6 @@ public class DisruptorReference {
         this.size = size;
         this.producerType = producerType;
         this.waitStrategy = waitStrategy;
-        temporaryExchangeBuffer = new ArrayBlockingQueue<>(size);
         reconfigure();
     }
 
@@ -135,11 +148,62 @@ public class DisruptorReference {
     }
 
     public void tryPublish(final Exchange exchange) throws 
DisruptorNotStartedException, InsufficientCapacityException {
-        tryPublishExchangeOnRingBuffer(exchange, 
getCurrentDisruptor().getRingBuffer());
+        final RingBuffer<ExchangeEvent> ringBuffer = 
beginPublish().getRingBuffer();
+        try {
+            tryPublishExchangeOnRingBuffer(exchange, ringBuffer);
+        } finally {
+            publishesInFlight.decrementAndGet();
+        }
     }
 
     public void publish(final Exchange exchange) throws 
DisruptorNotStartedException {
-        publishExchangeOnRingBuffer(exchange, 
getCurrentDisruptor().getRingBuffer());
+        final RingBuffer<ExchangeEvent> ringBuffer = 
beginPublish().getRingBuffer();
+        try {
+            publishExchangeOnRingBuffer(exchange, ringBuffer);
+        } finally {
+            publishesInFlight.decrementAndGet();
+        }
+    }
+
+    /**
+     * The current Disruptor, waiting while the Disruptor is being 
reconfigured. The caller is counted in
+     * {@link #publishesInFlight}, and must decrement it once it has published 
on its ring buffer, or failed to.
+     */
+    private Disruptor<ExchangeEvent> beginPublish() throws 
DisruptorNotStartedException {
+        while (true) {
+            // count, then read the reference: a reconfiguration clears the 
reference, then waits until the count is 0, so
+            // either it waits for this producer, or this producer sees the 
cleared reference
+            publishesInFlight.incrementAndGet();
+            final Disruptor<ExchangeEvent> currentDisruptor = 
disruptor.getReference();
+            if (currentDisruptor != null) {
+                return currentDisruptor;
+            }
+            publishesInFlight.decrementAndGet();
+            // wait for the reconfiguration to end without being counted (or 
fail if the Disruptor is not started)
+            getCurrentDisruptor();
+        }
+    }
+
+    private void awaitPublishesInFlight() {
+        // a producer in flight usually ends within microseconds, but one that 
waits for a free slot waits for a consumer:
+        // the pause doubles up to 1 ms, so a long wait does not keep a core 
busy. parkNanos returns at once while the
+        // interrupt flag is set, so on an interrupted thread (such as a 
CamelContext stop that timed out) the loop would
+        // spin: the flag is cleared for the wait, and set again after it
+        boolean interrupted = Thread.interrupted();
+        try {
+            long pause = 1000L;
+            while (publishesInFlight.get() > 0) {
+                LockSupport.parkNanos(pause);
+                pause = Math.min(pause * 2, MAX_PUBLISHES_IN_FLIGHT_PAUSE);
+                if (Thread.interrupted()) {
+                    interrupted = true;
+                }
+            }
+        } finally {
+            if (interrupted) {
+                Thread.currentThread().interrupt();
+            }
+        }
     }
 
     private void publishExchangeOnRingBuffer(
@@ -164,6 +228,7 @@ public class DisruptorReference {
             shutdownDisruptor(true);
 
             start();
+            startPublishingBufferedExchanges();
         } finally {
             lock.unlock();
         }
@@ -207,11 +272,101 @@ public class DisruptorReference {
         //switching a latch and we want to await that latch here to make sure 
they are started.
         awaitEventHandlers(handlers, true);
 
-        publishBufferedExchanges(newDisruptor);
+        // a Disruptor without consumer would only take the buffered exchanges 
back into the buffer when it is shut down,
+        // so they stay buffered, in order, for the first consumer
+        final boolean hasConsumers = getBlockingEventHandler() == null;
+        if (hasConsumers) {
+            // the buffered exchanges go first: as many as the ring buffer 
holds, before the producers can use it (this
+            // does not wait, as nothing else publishes on it yet). The rest 
is published by another thread once the
+            // reference is set (startPublishingBufferedExchanges), as 
publishing more than the ring buffer holds waits
+            // for its consumers, which may need a lock that is held here 
(this one, that of the endpoint, or that of
+            // the CamelContext that starts the route)
+            publishBufferedExchanges(newDisruptor.getRingBuffer());
+        }
 
+        consumingDisruptor = hasConsumers ? newDisruptor : null;
         disruptor.set(newDisruptor, false);
     }
 
+    /**
+     * Starts a thread that publishes the buffered exchanges that did not fit 
the ring buffer of the Disruptor that was
+     * just started, if there are any and it has consumers (the buffer holds 
more exchanges than the ring buffer when
+     * producers waited on the full ring buffer of a Disruptor without 
consumer). It publishes them as a producer does,
+     * without holding a lock, so that a consumer that needs one of the locks 
held while the Disruptor is started does
+     * not wait for the thread that started it. Called after {@link #start()}, 
outside of it, so that a failure here
+     * does not affect a Disruptor that producers already use: when the thread 
cannot be started, the exchanges stay
+     * buffered for the next start (a {@link VirtualMachineError} is thrown 
again).
+     */
+    private void startPublishingBufferedExchanges() {
+        if (!hasBufferedExchangesToPublish() || 
!publishingBufferedExchanges.compareAndSet(false, true)) {
+            // nothing to do, or the thread that already does it publishes 
these too
+            return;
+        }
+        try {
+            CamelContext context = executorContext != null ? executorContext : 
component.getCamelContext();
+            Thread thread = context.getExecutorServiceManager()
+                    .newThread("DisruptorBacklog[" + uri + "]", 
this::publishRestOfBufferedExchanges);
+            thread.start();
+        } catch (Throwable e) {
+            // such as the OutOfMemoryError of a thread that cannot be 
created: no thread publishes them, so the next
+            // start must be able to start one
+            publishingBufferedExchanges.set(false);
+            LOGGER.warn("Cannot start the thread that publishes the {} 
buffered exchanges of disruptor {}, they are"
+                        + " published when it is started again: {}",
+                    temporaryExchangeBuffer.size(), uri, e.toString());
+            if (e instanceof VirtualMachineError vme) {
+                throw vme;
+            }
+        }
+    }
+
+    private boolean hasBufferedExchangesToPublish() {
+        final Disruptor<ExchangeEvent> currentDisruptor = 
disruptor.getReference();
+        return currentDisruptor != null && currentDisruptor == 
consumingDisruptor && !temporaryExchangeBuffer.isEmpty();
+    }
+
+    private void publishRestOfBufferedExchanges() {
+        do {
+            try {
+                while (publishNextBufferedExchange()) {
+                    // publish the next one
+                }
+            } finally {
+                publishingBufferedExchanges.set(false);
+            }
+            // a Disruptor started while this thread was ending did not start 
another one: go on with its exchanges
+        } while (hasBufferedExchangesToPublish() && 
publishingBufferedExchanges.compareAndSet(false, true));
+    }
+
+    /**
+     * Publishes the first buffered exchange on the current Disruptor, as a 
producer does. Returns false, leaving the
+     * exchanges buffered, when there is none, when the current Disruptor has 
no consumer (the first consumer gets them,
+     * in order) or when it is not started (the next start publishes them).
+     */
+    private boolean publishNextBufferedExchange() {
+        final Disruptor<ExchangeEvent> currentDisruptor;
+        try {
+            currentDisruptor = beginPublish();
+        } catch (DisruptorNotStartedException e) {
+            return false;
+        }
+        try {
+            if (currentDisruptor != consumingDisruptor || 
temporaryExchangeBuffer.isEmpty()) {
+                return false;
+            }
+            // only this thread and start() take exchanges from the buffer, 
and start() runs only after a reconfiguration
+            // has waited for this thread (counted in publishesInFlight): the 
first exchange is still there once a slot
+            // is free, and is published before the ones behind it
+            final RingBuffer<ExchangeEvent> ringBuffer = 
currentDisruptor.getRingBuffer();
+            final long sequence = ringBuffer.next();
+            
ringBuffer.get(sequence).setExchange(temporaryExchangeBuffer.poll(), 
uniqueConsumerCount);
+            ringBuffer.publish(sequence);
+            return true;
+        } finally {
+            publishesInFlight.decrementAndGet();
+        }
+    }
+
     private Disruptor<ExchangeEvent> createDisruptor() throws Exception {
         //create a new Disruptor
         final Disruptor<ExchangeEvent> newDisruptor = new Disruptor<>(
@@ -258,19 +413,23 @@ public class DisruptorReference {
         newDisruptor.handleEventsWith(handlers);
     }
 
-    private void publishBufferedExchanges(Disruptor<ExchangeEvent> 
newDisruptor) {
-        //now empty out all buffered Exchange if we had any
-        final List<Exchange> exchanges = new 
ArrayList<>(temporaryExchangeBuffer.size());
-        while (!temporaryExchangeBuffer.isEmpty()) {
-            exchanges.add(temporaryExchangeBuffer.remove());
-        }
-        RingBuffer<ExchangeEvent> ringBuffer = newDisruptor.getRingBuffer();
-        //and offer them again to our new ringbuffer
-        for (final Exchange exchange : exchanges) {
+    private void publishBufferedExchanges(RingBuffer<ExchangeEvent> 
ringBuffer) {
+        Exchange exchange;
+        while (ringBuffer.remainingCapacity() > 0 && (exchange = 
temporaryExchangeBuffer.poll()) != null) {
             publishExchangeOnRingBuffer(exchange, ringBuffer);
         }
     }
 
+    /**
+     * The event handler that keeps a Disruptor without consumer busy, or null 
if the Disruptor has consumers.
+     */
+    private BlockingExchangeEventHandler getBlockingEventHandler() {
+        if (handlers.length == 1 && handlers[0] instanceof 
BlockingExchangeEventHandler blockingExchangeEventHandler) {
+            return blockingExchangeEventHandler;
+        }
+        return null;
+    }
+
     /**
      * The CamelContext to create the threads of the event handlers with: the 
CamelContext of an endpoint that uses this
      * Disruptor (with disruptor-vm, the endpoints can belong to several 
CamelContexts), else that of the component that
@@ -339,13 +498,19 @@ public class DisruptorReference {
 
             if (currentDisruptor != null) {
                 //check if we had a blocking event handler to keep an empty 
disruptor 'busy'
-                if (handlers != null && handlers.length == 1
-                        && handlers[0] instanceof BlockingExchangeEventHandler 
blockingExchangeEventHandler) {
+                BlockingExchangeEventHandler blockingExchangeEventHandler = 
getBlockingEventHandler();
+                if (blockingExchangeEventHandler != null) {
                     // yes we did, unblock it so we can get rid of our backlog,
                     // The eventhandler will empty its pending exchanges in 
our temporary buffer
                     blockingExchangeEventHandler.unblock();
                 }
 
+                // the producers that read the reference before it was cleared 
publish on this ring buffer, also those
+                // that wait for a free slot on a full ring buffer (the event 
handlers keep running until the shutdown
+                // below, and a blocking event handler was unblocked above): 
wait for them, so the shutdown drains their
+                // exchanges, instead of halting the event handlers before 
they are published
+                awaitPublishesInFlight();
+
                 currentDisruptor.shutdown();
 
                 //they have already been given a trigger to halt when they are 
done by shutting down the disruptor
@@ -473,6 +638,7 @@ public class DisruptorReference {
                     registeredEndpoints.set(endpoints.size());
                     throw RuntimeCamelException.wrapRuntimeCamelException(e);
                 }
+                startPublishingBufferedExchanges();
             }
             LOGGER.debug("Endpoint added: {}, new total endpoints {}", 
disruptorEndpoint, endpoints.size());
         } finally {
@@ -509,6 +675,7 @@ public class DisruptorReference {
                 } catch (Exception e) {
                     throw RuntimeCamelException.wrapRuntimeCamelException(e);
                 }
+                startPublishingBufferedExchanges();
             }
         } finally {
             lock.unlock();
@@ -571,6 +738,7 @@ public class DisruptorReference {
                 // the producer no longer waits for this exchange (timeout), 
so don't process it
                 LOGGER.trace("Ignoring exchange {}", exchange);
             } else {
+                // not bounded, so this never drops the exchange
                 temporaryExchangeBuffer.offer(exchange);
             }
         }
diff --git 
a/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorReconfigureWithWaitingProducersTest.java
 
b/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorReconfigureWithWaitingProducersTest.java
new file mode 100644
index 000000000000..4f3933287283
--- /dev/null
+++ 
b/components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorReconfigureWithWaitingProducersTest.java
@@ -0,0 +1,446 @@
+/*
+ * 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.lang.management.ManagementFactory;
+import java.lang.management.ThreadMXBean;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+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.impl.engine.DefaultExecutorServiceManager;
+import org.apache.camel.test.junit6.CamelTestSupport;
+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.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;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
+/**
+ * Producers that wait for a free slot on the full ring buffer of a disruptor 
while a consumer is added (which replaces
+ * the ring buffer) publish on the old ring buffer. Their exchanges must be 
processed (and not left on the old ring
+ * buffer after its event handlers were halted), and the reconfiguration must 
not wait for them forever.
+ */
+class DisruptorReconfigureWithWaitingProducersTest extends CamelTestSupport {
+
+    // a ring buffer of one slot: each exchange the slow consumer finishes 
empties it while producers wait for the slot
+    private static final String SLOW = 
"disruptor:slow?multipleConsumers=true&size=1";
+    private static final int SLOW_WAITING = 8;
+    private static final int NO_CONSUMER_SIZE = 4;
+    private static final String NO_CONSUMER = "disruptor:idle?size=" + 
NO_CONSUMER_SIZE;
+    private static final String SMALL = 
"disruptor:small?multipleConsumers=true&size=2";
+
+    private final CountDownLatch releaseSlowConsumer = new CountDownLatch(1);
+    private final CountDownLatch releaseFirstConsumer = new CountDownLatch(1);
+    private final AtomicBoolean firstExchange = new AtomicBoolean(true);
+    private final List<Thread> producers = new ArrayList<>();
+    private final List<AtomicReference<Throwable>> failures = new 
ArrayList<>();
+    // thrown, once, when the CamelContext is asked for the thread that 
publishes the rest of a backlog
+    private final AtomicReference<Error> backlogThreadError = new 
AtomicReference<>();
+
+    @AfterEach
+    void release() {
+        releaseSlowConsumer.countDown();
+        releaseFirstConsumer.countDown();
+        // a producer that waits forever for its reply (on a failure) must not 
keep the test running
+        producers.forEach(Thread::interrupt);
+    }
+
+    @Test
+    void producersWaitingOnTheFullRingBufferWhileAConsumerIsAddedAreNotLost() 
throws Exception {
+        MockEndpoint slow = getMockEndpoint("mock:slow");
+        MockEndpoint added = getMockEndpoint("mock:added");
+        List<String> bodies = fillAndWait(SLOW, 1, SLOW_WAITING, false);
+        bodies.add("after");
+        slow.expectedBodiesReceivedInAnyOrder(bodies);
+        added.expectedBodiesReceived("after");
+
+        // the consumer of the slow route is busy and the ring buffer is full: 
a second consumer is added, which waits
+        // for the old ring buffer to be drained
+        Thread reconfiguration = addRouteInBackground(SLOW, "mock:added");
+        DisruptorReference reference = context.getEndpoint(SLOW, 
DisruptorEndpoint.class).getDisruptor();
+        await().atMost(20, 
TimeUnit.SECONDS).until(reference::hasNullReference);
+
+        // the slow consumer frees the slots of the old ring buffer, which the 
waiting producers take
+        releaseSlowConsumer.countDown();
+
+        awaitEnded(reconfiguration);
+        producers.forEach(this::awaitEnded);
+        template.sendBody(SLOW, "after");
+
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+    }
+
+    @Test
+    void aReconfigurationWaitsForTheProducersWithoutSpinning() throws 
Exception {
+        reconfigurationWaitsForTheProducersWithoutSpinning(false);
+    }
+
+    @Test
+    void 
aReconfigurationOnAnInterruptedThreadWaitsForTheProducersWithoutSpinning() 
throws Exception {
+        // as a CamelContext stop that timed out
+        reconfigurationWaitsForTheProducersWithoutSpinning(true);
+    }
+
+    private void reconfigurationWaitsForTheProducersWithoutSpinning(boolean 
interrupted) throws Exception {
+        ThreadMXBean threads = ManagementFactory.getThreadMXBean();
+        assumeTrue(threads.isThreadCpuTimeSupported() && 
threads.isThreadCpuTimeEnabled());
+        List<String> bodies = fillAndWait(SLOW, 1, SLOW_WAITING, false);
+        getMockEndpoint("mock:slow").expectedBodiesReceivedInAnyOrder(bodies);
+
+        // a consumer is added: the reconfiguration waits for the producers in 
flight, which wait for the busy slow
+        // consumer
+        AtomicBoolean interruptedAfter = new AtomicBoolean();
+        Thread reconfiguration = new Thread(() -> {
+            if (interrupted) {
+                Thread.currentThread().interrupt();
+            }
+            try {
+                context.addRoutes(new RouteBuilder() {
+                    @Override
+                    public void configure() {
+                        from(SLOW).routeId("added").to("mock:added");
+                    }
+                });
+            } catch (Exception e) {
+                throw new IllegalStateException(e);
+            }
+            interruptedAfter.set(Thread.currentThread().isInterrupted());
+        }, "add-consumer");
+        reconfiguration.setDaemon(true);
+        reconfiguration.start();
+        DisruptorReference reference = context.getEndpoint(SLOW, 
DisruptorEndpoint.class).getDisruptor();
+        await().atMost(20, 
TimeUnit.SECONDS).until(reference::hasNullReference);
+
+        // the CPU time the reconfiguration uses while it waits half a second: 
parked, not spinning
+        long cpuBefore = threads.getThreadCpuTime(reconfiguration.threadId());
+        long waitStart = System.nanoTime();
+        await().pollDelay(500, TimeUnit.MILLISECONDS).atMost(20, 
TimeUnit.SECONDS).until(() -> true);
+        long waited = System.nanoTime() - waitStart;
+        long cpu = threads.getThreadCpuTime(reconfiguration.threadId()) - 
cpuBefore;
+        releaseSlowConsumer.countDown();
+
+        awaitEnded(reconfiguration);
+        producers.forEach(this::awaitEnded);
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+        assertTrue(cpu < waited / 2,
+                () -> "the reconfiguration used " + 
TimeUnit.NANOSECONDS.toMillis(cpu) + " ms of CPU in "
+                      + TimeUnit.NANOSECONDS.toMillis(waited) + " ms of 
waiting");
+        assertEquals(interrupted, interruptedAfter.get(), "the interrupt flag 
of the thread is kept");
+    }
+
+    @Test
+    void 
requestReplyProducersWaitingOnTheFullRingBufferWhileAConsumerIsAddedGetTheirReply()
 throws Exception {
+        List<String> bodies = fillAndWait(SLOW, 1, SLOW_WAITING, true);
+        getMockEndpoint("mock:slow").expectedBodiesReceivedInAnyOrder(bodies);
+
+        Thread reconfiguration = addRouteInBackground(SLOW, "mock:added");
+        DisruptorReference reference = context.getEndpoint(SLOW, 
DisruptorEndpoint.class).getDisruptor();
+        await().atMost(20, 
TimeUnit.SECONDS).until(reference::hasNullReference);
+        releaseSlowConsumer.countDown();
+
+        // the request/reply producers wait without timeout: each must get the 
reply of the slow route
+        awaitEnded(reconfiguration);
+        producers.forEach(this::awaitEnded);
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+    }
+
+    @Test
+    void 
producersWaitingOnTheFullRingBufferOfAQueueWithoutConsumerAreNotLostWhenTheFirstConsumerStarts()
+            throws Exception {
+        MockEndpoint first = getMockEndpoint("mock:first");
+        List<String> bodies = fillAndWait(NO_CONSUMER, NO_CONSUMER_SIZE, 
NO_CONSUMER_SIZE, false);
+        // the exchanges sent before the consumer started, the ones that 
waited for a free slot after them
+        first.expectedBodiesReceivedInAnyOrder(bodies);
+
+        // the queue has no consumer, so nothing frees a slot until the 
consumer starts: the reconfiguration must not
+        // wait for the producers that wait for a slot on the old ring buffer 
forever
+        Thread reconfiguration = addRouteInBackground(NO_CONSUMER, 
"mock:first");
+        awaitEnded(reconfiguration);
+        producers.forEach(this::awaitEnded);
+
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+        // the backlog is delivered first, in the order it was sent
+        for (int i = 0; i < NO_CONSUMER_SIZE; i++) {
+            assertEquals("backlog-" + i, 
first.getReceivedExchanges().get(i).getMessage().getBody());
+        }
+    }
+
+    @Test
+    void 
consumerThatTakesTheLockOfItsQueueWhileTheRestOfTheBacklogIsPublishedDoesNotBlockItsStart()
 throws Exception {
+        MockEndpoint first = getMockEndpoint("mock:first");
+        // more exchanges than the ring buffer holds wait for the first 
consumer
+        List<String> bodies = fillAndWait(SMALL, 2, 2, false);
+        first.expectedBodiesReceivedInAnyOrder(bodies);
+
+        // on its first exchange, the consumer creates an endpoint of its own 
queue with other options (as a toD would),
+        // which takes the lock of the disruptor: the start of its route must 
not wait for this consumer with the lock
+        // held, which would block both for good
+        Thread reconfiguration = addRouteInBackground(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(SMALL).routeId("added").process(e -> {
+                    if (firstExchange.getAndSet(false)) {
+                        e.getContext().getEndpoint(SMALL + "&timeout=4321");
+                    }
+                }).to("mock:first");
+            }
+        });
+        awaitEnded(reconfiguration);
+        producers.forEach(this::awaitEnded);
+
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+        // the backlog that fits the ring buffer is delivered first, in the 
order it was sent
+        assertEquals("backlog-0", 
first.getReceivedExchanges().get(0).getMessage().getBody());
+        assertEquals("backlog-1", 
first.getReceivedExchanges().get(1).getMessage().getBody());
+    }
+
+    @Test
+    void consumerAddedWhileTheRestOfTheBacklogIsPublishedGetsTheRestOnce() 
throws Exception {
+        MockEndpoint first = getMockEndpoint("mock:first");
+        MockEndpoint second = getMockEndpoint("mock:second");
+        List<String> bodies = fillAndWait(SMALL, 2, 4, false);
+        first.expectedBodiesReceivedInAnyOrder(bodies);
+
+        // the first consumer holds the first exchange: the ring buffer stays 
full with the backlog, and the thread that
+        // publishes the rest of it waits for a free slot
+        Thread reconfiguration = addRouteInBackground(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(SMALL).routeId("first").process(e -> 
releaseFirstConsumer.await(20, TimeUnit.SECONDS))
+                        .to("mock:first");
+            }
+        });
+        awaitEnded(reconfiguration);
+        await().atMost(20, TimeUnit.SECONDS).until(() -> 
Thread.getAllStackTraces().keySet().stream()
+                .anyMatch(t -> isBacklogThreadOfThisContext(t) && 
isWaitingForFreeSlot(t)));
+
+        // a second consumer is added meanwhile: the reconfiguration waits for 
that thread, which publishes on the old
+        // ring buffer once the first consumer goes on, and then the rest on 
the new one
+        Thread secondReconfiguration = addRouteInBackground(new RouteBuilder() 
{
+            @Override
+            public void configure() {
+                from(SMALL).routeId("second").to("mock:second");
+            }
+        });
+        DisruptorReference reference = context.getEndpoint(SMALL, 
DisruptorEndpoint.class).getDisruptor();
+        await().atMost(20, 
TimeUnit.SECONDS).until(reference::hasNullReference);
+        releaseFirstConsumer.countDown();
+        awaitEnded(secondReconfiguration);
+        producers.forEach(this::awaitEnded);
+
+        // each exchange once, in the order of the buffer: the backlog and one 
more on the old ring buffer, the 3 others
+        // on the new one, which the second consumer gets too
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+        List<Object> received = first.getReceivedExchanges().stream().map(e -> 
e.getMessage().getBody()).toList();
+        assertEquals(List.of("backlog-0", "backlog-1"), received.subList(0, 
2));
+        await().atMost(20, TimeUnit.SECONDS).until(() -> 
second.getReceivedCounter() >= 3);
+        assertEquals(received.subList(3, 6),
+                second.getReceivedExchanges().stream().map(e -> 
e.getMessage().getBody()).toList());
+    }
+
+    @Test
+    void restOfTheBacklogStaysBufferedWhenItsThreadCannotBeStarted() throws 
Exception {
+        MockEndpoint first = getMockEndpoint("mock:first");
+        List<String> bodies = fillAndWait(SMALL, 2, 4, false);
+        first.expectedBodiesReceivedInAnyOrder(bodies);
+
+        // the first consumer route is added, but the thread that would 
publish what does not fit the ring buffer
+        // cannot be started (an Error that is not a VirtualMachineError; an 
OutOfMemoryError, such as when no native
+        // thread can be created, is thrown again): the route starts, the 
consumer gets what fits the ring buffer, and
+        // the rest stays buffered
+        backlogThreadError.set(new CannotStartThreadError());
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(SMALL).routeId("first").to("mock:first");
+            }
+        });
+        producers.forEach(this::awaitEnded);
+        await().atMost(20, TimeUnit.SECONDS).until(() -> 
first.getReceivedCounter() == 2);
+        assertNull(backlogThreadError.get());
+
+        // the next reconfiguration publishes what fits its ring buffer and 
starts the thread for the rest (if the
+        // failure had left the thread marked as running, no thread would 
publish the last 2)
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(SMALL).routeId("second").to("mock:second");
+            }
+        });
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+        List<Object> received = first.getReceivedExchanges().stream().map(e -> 
e.getMessage().getBody()).toList();
+        assertEquals(List.of("backlog-0", "backlog-1"), received.subList(0, 
2));
+    }
+
+    /**
+     * Fills the ring buffer of the endpoint (of the given size), then starts 
the given number of producers, and waits
+     * until they all wait for a free slot. Returns the bodies of all the 
exchanges sent.
+     */
+    private List<String> fillAndWait(String uri, int size, int 
waitingProducers, boolean requestReply) {
+        List<String> bodies = new ArrayList<>();
+        for (int i = 0; i < size; i++) {
+            String body = "backlog-" + i;
+            if (requestReply) {
+                producers.add(startProducer("backlog-producer-" + i, uri + 
"&timeout=0", body, true));
+            } else {
+                template.sendBody(uri, body);
+            }
+            bodies.add(body);
+        }
+        if (requestReply) {
+            // the slow consumer holds the first exchange, the others fill the 
ring buffer
+            await().atMost(20, TimeUnit.SECONDS)
+                    .until(() -> 
getMockEndpoint("mock:slow").getReceivedCounter() == 0 && 
remainingCapacity(uri) == 0);
+        }
+        List<Thread> waiting = new ArrayList<>();
+        for (int i = 0; i < waitingProducers; i++) {
+            String body = "waiting-" + i;
+            Thread producer = startProducer("waiting-producer-" + i, uri + 
(requestReply ? "&timeout=0" : ""), body,
+                    requestReply);
+            waiting.add(producer);
+            producers.add(producer);
+            bodies.add(body);
+        }
+        await().atMost(20, TimeUnit.SECONDS).until(() -> 
waiting.stream().allMatch(this::isWaitingForFreeSlot));
+        return bodies;
+    }
+
+    private long remainingCapacity(String uri) throws Exception {
+        return context.getEndpoint(uri, 
DisruptorEndpoint.class).getDisruptor().getRemainingCapacity();
+    }
+
+    private Thread startProducer(String name, String uri, String body, boolean 
requestReply) {
+        AtomicReference<Throwable> failure = new AtomicReference<>();
+        Thread producer = new Thread(() -> {
+            try {
+                if (requestReply) {
+                    Object reply = template.requestBody(uri, body);
+                    if (!body.equals(reply)) {
+                        failure.set(new AssertionError("Unexpected reply " + 
reply + " to " + body));
+                    }
+                } else {
+                    template.sendBody(uri, body);
+                }
+            } catch (Exception e) {
+                failure.set(e);
+            }
+        }, name);
+        producer.setDaemon(true);
+        producer.start();
+        failures.add(failure);
+        return producer;
+    }
+
+    private boolean isBacklogThreadOfThisContext(Thread thread) {
+        // "Camel (camel-N) thread #M - DisruptorBacklog[...]": not the thread 
of a disruptor test in another context
+        String name = thread.getName();
+        return name.contains("(" + context.getName() + ")") && 
name.contains("DisruptorBacklog[");
+    }
+
+    private boolean isWaitingForFreeSlot(Thread thread) {
+        for (StackTraceElement element : thread.getStackTrace()) {
+            // MultiProducerSequencer.next() parks until a slot is free
+            if ("next".equals(element.getMethodName()) && 
element.getClassName().startsWith("com.lmax.disruptor.")
+                    && element.getClassName().endsWith("Sequencer")) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private Thread addRouteInBackground(String uri, String to) {
+        return addRouteInBackground(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(uri).routeId("added").to(to);
+            }
+        });
+    }
+
+    private Thread addRouteInBackground(RouteBuilder routes) {
+        Thread reconfiguration = new Thread(() -> {
+            try {
+                context.addRoutes(routes);
+            } catch (Exception e) {
+                throw new IllegalStateException(e);
+            }
+        }, "add-consumer");
+        reconfiguration.setDaemon(true);
+        reconfiguration.start();
+        return reconfiguration;
+    }
+
+    private void awaitEnded(Thread thread) {
+        await().atMost(20, TimeUnit.SECONDS).until(() -> !thread.isAlive());
+        assertFalse(thread.isAlive(), thread.getName() + " is still running");
+        for (AtomicReference<Throwable> failure : failures) {
+            assertNull(failure.get());
+        }
+    }
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext camelContext = super.createCamelContext();
+        camelContext.setExecutorServiceManager(new 
DefaultExecutorServiceManager(camelContext) {
+            @Override
+            public Thread newThread(String name, Runnable runnable) {
+                if (name.startsWith("DisruptorBacklog")) {
+                    Error error = backlogThreadError.getAndSet(null);
+                    if (error != null) {
+                        throw error;
+                    }
+                }
+                return super.newThread(name, runnable);
+            }
+        });
+        return camelContext;
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(SLOW).routeId("slow")
+                        .process(e -> releaseSlowConsumer.await(20, 
TimeUnit.SECONDS))
+                        .to("mock:slow");
+            }
+        };
+    }
+
+    /**
+     * An error that the thread that publishes the rest of a backlog cannot be 
started with.
+     */
+    private static final class CannotStartThreadError extends Error {
+        private static final long serialVersionUID = 1L;
+
+        CannotStartThreadError() {
+            super("cannot start the thread");
+        }
+    }
+}

Reply via email to