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 3d848bec9c80 CAMEL-27502: camel-hazelcast - stopping a transacted 
hazelcast-seda route waits for the exchange in progress instead of rolling it 
back (#30816)
3d848bec9c80 is described below

commit 3d848bec9c801bfe04fd9ffe18d5e74f0725511e
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 13:29:36 2026 +0530

    CAMEL-27502: camel-hazelcast - stopping a transacted hazelcast-seda route 
waits for the exchange in progress instead of rolling it back (#30816)
    
    When the route of a transacted Hazelcast SEDA consumer stopped while an
    exchange was being routed, doStop shut the consumer threads down with
    shutdownGraceful, which interrupts them after shutdownAwaitTermination
    (10 s by default). The shutdown strategy stops the consumer before it
    waits for the exchanges in flight (45 s by default), so a longer exchange
    was interrupted: with a route that continues on another thread the
    consumer thread stopped waiting for it and rolled the transaction back
    while the exchange went on and completed, and a synchronous route was
    aborted and rolled back. Either way the message was back at the head of
    the queue and was processed again after the restart or by another
    member.
    
    In transacted mode a consumer thread now counts itself before it polls
    (under a lock, with the isRunAllowed check) until the transaction of its
    exchange has ended, and doStop first waits until no thread polls or
    routes, at most the timeout of the shutdown strategy, then shuts the
    threads down as before. A stop that waits for an exchange logs one INFO
    line. An exchange still routed when that timeout expires, or when the
    shutdown strategy times out and cancels the stop, is rolled back as
    before (with a WARN of the consumer or of the shutdown strategy). The delay 
after an error starts after the
    thread uncounted itself, so the stop does not wait for it, and it is
    skipped when the consumer is stopping: a thread the stop no longer
    waits for started it on the scheduler the stop had already shut down.
    The scheduler field is volatile. The stop does not wait when the
    shutdown strategy has timed out and stops the remaining consumers at
    once (a deferred route, or a route the timed out shutdown had not
    reached yet), and a consumer thread that stops the consumer itself (a
    route policy when its exchange completes) does not wait for itself. The
    non-transacted consumer is not changed.
    
    Test: HazelcastSedaTransactedStopTest stops the route while a step runs
    (with threads() and synchronous): for longer than the 1 s graceful
    timeout of the test the message must stay out of the queue and the stop
    must wait; after the step completes the message is committed and a
    restart does not consume it again. A control checks the rollback when
    the exchange outlasts a 2 s shutdown timeout. Two more check that a
    forced stop after the shutdown timeout of a deferred route does not wait
    another timeout, and that a route policy that stops the consumer when
    its exchange completes is not held up by the stop.
    
    Not changed: a message that always fails is taken again after every
    rollback without a limit, and a non-transacted consumer with an
    asynchronous route does not bound its exchanges in flight.
    
    * CAMEL-27502: camel-hazelcast - review follow-up: create the exchange 
before counting the transacted thread
    
    - HazelcastSedaConsumer: the consumer thread creates its exchange before
      beginTransacted() registers it, and releases the exchange when the 
consumer is
      stopping. Before, an exception from createExchange() left the thread 
counted, and
      the stop waited for it until the shutdown timeout.
    - HazelcastSedaTransactedStopTest: a new test fails the creation of the 
consumer's
      exchange once (an exchange factory that throws) and checks that stopping 
the
      route does not wait for the thread.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../hazelcast/seda/HazelcastSedaConsumer.java      | 138 +++++++++-
 .../hazelcast/HazelcastSedaTransactedStopTest.java | 279 +++++++++++++++++++++
 2 files changed, 408 insertions(+), 9 deletions(-)

diff --git 
a/components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/seda/HazelcastSedaConsumer.java
 
b/components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/seda/HazelcastSedaConsumer.java
index d6e22d347dcd..f424cf22f635 100644
--- 
a/components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/seda/HazelcastSedaConsumer.java
+++ 
b/components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/seda/HazelcastSedaConsumer.java
@@ -17,9 +17,14 @@
 package org.apache.camel.component.hazelcast.seda;
 
 import java.time.Duration;
+import java.util.HashSet;
+import java.util.Set;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
 
 import com.hazelcast.collection.BaseQueue;
 import com.hazelcast.transaction.TransactionContext;
@@ -29,6 +34,7 @@ import org.apache.camel.Consumer;
 import org.apache.camel.Endpoint;
 import org.apache.camel.Exchange;
 import org.apache.camel.Processor;
+import org.apache.camel.spi.ShutdownStrategy;
 import org.apache.camel.support.AsyncProcessorConverterHelper;
 import org.apache.camel.support.DefaultConsumer;
 import org.apache.camel.support.DefaultExchange;
@@ -51,8 +57,15 @@ public class HazelcastSedaConsumer extends DefaultConsumer 
implements Runnable {
     private final HazelcastSedaEndpoint endpoint;
     private final AsyncProcessor processor;
     private ExecutorService executor;
-    private ScheduledExecutorService taskExecutor;
+    // read by the consumer threads, which can still run after doStop when the 
stop was interrupted
+    private volatile ScheduledExecutorService taskExecutor;
     private volatile boolean transferredExchangeLogged;
+    // the transacted consumer threads that poll or route a polled exchange, 
guarded by transactedLock: the stop waits
+    // for them before it shuts the threads down, as the shutdown interrupts a 
thread that waits for its exchange, which
+    // rolls back the transaction of an exchange that still completes (so its 
message is consumed again)
+    private final Lock transactedLock = new ReentrantLock();
+    private final Condition transactedDone = transactedLock.newCondition();
+    private final Set<Thread> transactedThreads = new HashSet<>();
 
     public HazelcastSedaConsumer(final Endpoint endpoint, final Processor 
processor) {
         super(endpoint, processor);
@@ -77,6 +90,9 @@ public class HazelcastSedaConsumer extends DefaultConsumer 
implements Runnable {
     @Override
     protected void doStop() throws Exception {
         if (executor != null) {
+            if (endpoint.getConfiguration().isTransacted()) {
+                awaitTransactedExchanges();
+            }
             // wait for the consumer threads to end their current poll (at 
most MAX_POLL_WAIT) and route what it returned:
             // a poll takes the item from the queue, so an item polled after 
the processor is stopped is lost
             
endpoint.getCamelContext().getExecutorServiceManager().shutdownGraceful(executor);
@@ -103,8 +119,16 @@ public class HazelcastSedaConsumer extends DefaultConsumer 
implements Runnable {
         while (queue != null && isRunAllowed()) {
             final boolean transacted = 
endpoint.getConfiguration().isTransacted();
             // the transacted consumer reads the outcome of the exchange after 
the routing is done, so it releases the
-            // exchange itself: a pooled exchange is otherwise reset (and its 
exception cleared) when it is done
+            // exchange itself: a pooled exchange is otherwise reset (and its 
exception cleared) when it is done.
+            // Created before beginTransacted, so a failure to create it does 
not leave this thread counted: the stop
+            // would wait for it until the shutdown timeout
             final Exchange exchange = createExchange(!transacted);
+            if (transacted && !beginTransacted()) {
+                // the consumer is stopping
+                releaseExchange(exchange, false);
+                break;
+            }
+            boolean errorDelay = false;
 
             TransactionContext transactionCtx = null;
             try {
@@ -139,11 +163,9 @@ public class HazelcastSedaConsumer extends DefaultConsumer 
implements Runnable {
                             } catch (Exception e) {
                                 exchange.setException(e);
                             }
-                            if (onExchangeDone(exchange, txc)) {
-                                // the message is back on the queue: wait 
before taking it again, or a message that
-                                // always fails is taken and rolled back in a 
tight loop
-                                waitOnErrorDelay();
-                            }
+                            // when the message is back on the queue, wait 
before taking it again, or a message that
+                            // always fails is taken and rolled back in a 
tight loop
+                            errorDelay = onExchangeDone(exchange, txc);
                         } else {
                             // process using the asynchronous routing engine
                             processor.process(exchange, new AsyncCallback() {
@@ -194,13 +216,105 @@ public class HazelcastSedaConsumer extends 
DefaultConsumer implements Runnable {
                     }
                 }
                 getExceptionHandler().handleException("Error processing 
exchange", exchange, e);
-                waitOnErrorDelay();
+                errorDelay = true;
             } finally {
                 if (transacted) {
                     releaseExchange(exchange, false);
+                    endTransacted();
                 }
             }
+            if (errorDelay) {
+                // after endTransacted: the stop does not wait for the delay
+                waitOnErrorDelay();
+            }
+        }
+    }
+
+    /**
+     * Counts a transacted consumer thread that polls and routes, unless the 
consumer is stopping (checked under the
+     * lock, so the stop either waits for this thread or this thread does not 
poll).
+     */
+    private boolean beginTransacted() {
+        transactedLock.lock();
+        try {
+            if (!isRunAllowed()) {
+                return false;
+            }
+            transactedThreads.add(Thread.currentThread());
+            return true;
+        } finally {
+            transactedLock.unlock();
+        }
+    }
+
+    private void endTransacted() {
+        transactedLock.lock();
+        try {
+            transactedThreads.remove(Thread.currentThread());
+            transactedDone.signalAll();
+        } finally {
+            transactedLock.unlock();
+        }
+    }
+
+    /**
+     * Waits until no transacted consumer thread polls or routes an exchange, 
at most the timeout of the shutdown
+     * strategy, and not at all when the shutdown strategy has timed out and 
forces the consumers to stop. The shutdown
+     * of the consumer threads that follows interrupts a thread that is still 
waiting for its exchange, and the
+     * transaction of that exchange is then rolled back.
+     */
+    private void awaitTransactedExchanges() {
+        ShutdownStrategy strategy = 
endpoint.getCamelContext().getShutdownStrategy();
+        if (strategy.isForceShutdown() || strategy.isTimeoutOccurred()) {
+            // the graceful shutdown timed out, and stops the remaining 
consumers now: do not wait again
+            LOG.debug("Not waiting for the transacted exchanges of {}: the 
shutdown is forced", endpoint);
+            return;
+        }
+        long timeoutMillis = 
strategy.getTimeUnit().toMillis(strategy.getTimeout());
+        long remaining = TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
+        transactedLock.lock();
+        try {
+            // a thread that only polls is done within MAX_POLL_WAIT (and its 
commit): say why the stop waits longer
+            long quiet = Math.min(remaining, TimeUnit.MILLISECONDS.toNanos(2 * 
MAX_POLL_WAIT));
+            remaining -= quiet - awaitTransactedDone(quiet);
+            if (transactedPending() > 0 && remaining > 0) {
+                LOG.info("Waiting up to {} ms for {} transacted exchanges of 
{} to complete before the consumer stops",
+                        TimeUnit.NANOSECONDS.toMillis(remaining), 
transactedPending(), endpoint);
+                awaitTransactedDone(remaining);
+            }
+            if (transactedPending() > 0) {
+                LOG.warn("Timeout waiting for {} transacted exchanges of {} to 
complete: the consumer stops now, and"
+                         + " their transactions are rolled back, so their 
messages are consumed again",
+                        transactedPending(), endpoint);
+            }
+        } catch (InterruptedException e) {
+            // the shutdown timed out (it cancels its task): stop now, which 
rolls back the remaining exchanges
+            LOG.debug("Interrupted while waiting for the transacted exchanges 
of {} to complete", endpoint);
+            Thread.currentThread().interrupt();
+        } finally {
+            transactedLock.unlock();
+        }
+    }
+
+    /**
+     * Waits (holding transactedLock) until no transacted consumer thread 
polls or routes, at most the given time.
+     *
+     * @return the time left
+     */
+    private long awaitTransactedDone(long nanos) throws InterruptedException {
+        while (transactedPending() > 0 && nanos > 0) {
+            nanos = transactedDone.awaitNanos(nanos);
         }
+        return Math.max(0, nanos);
+    }
+
+    /**
+     * The transacted consumer threads that the stop waits for (holding 
transactedLock): not the thread that stops, when
+     * a consumer thread stops the consumer itself (a route policy when its 
exchange completes), as it cannot end its
+     * exchange while it waits.
+     */
+    private int transactedPending() {
+        return transactedThreads.size() - 
(transactedThreads.contains(Thread.currentThread()) ? 1 : 0);
     }
 
     /**
@@ -228,6 +342,12 @@ public class HazelcastSedaConsumer extends DefaultConsumer 
implements Runnable {
      * Waits onErrorDelay before the consumer polls again, after an error or a 
rolled back transaction.
      */
     private void waitOnErrorDelay() {
+        final ScheduledExecutorService scheduler = taskExecutor;
+        if (scheduler == null || !isRunAllowed()) {
+            // the consumer is stopping, so the loop ends instead of polling 
again (and the scheduler may be shut down
+            // already, when the stop did not wait for this thread)
+            return;
+        }
         // Use Camel's task API for error recovery delay instead of 
Thread.sleep()
         // We use initialDelay for the actual delay, and maxIterations(1) to 
run once
         Tasks.backgroundTask()
@@ -237,7 +357,7 @@ public class HazelcastSedaConsumer extends DefaultConsumer 
implements Runnable {
                         .withInterval(Duration.ofMillis(1))
                         .withUnlimitedDuration()
                         .build())
-                .withScheduledExecutor(taskExecutor)
+                .withScheduledExecutor(scheduler)
                 .withName("HazelcastSedaErrorRecoveryDelay")
                 .build()
                 .run(getEndpoint().getCamelContext(), () -> true);
diff --git 
a/components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastSedaTransactedStopTest.java
 
b/components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastSedaTransactedStopTest.java
new file mode 100644
index 000000000000..72a98545ceb5
--- /dev/null
+++ 
b/components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastSedaTransactedStopTest.java
@@ -0,0 +1,279 @@
+/*
+ * 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.hazelcast;
+
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.hazelcast.collection.IQueue;
+import com.hazelcast.config.Config;
+import com.hazelcast.core.Hazelcast;
+import com.hazelcast.core.HazelcastInstance;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Consumer;
+import org.apache.camel.Endpoint;
+import org.apache.camel.Exchange;
+import org.apache.camel.Route;
+import org.apache.camel.ShutdownRoute;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.engine.PrototypeExchangeFactory;
+import org.apache.camel.spi.ExchangeFactory;
+import org.apache.camel.support.RoutePolicySupport;
+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.assertTrue;
+
+/**
+ * Stopping the route of a transacted Hazelcast SEDA consumer while an 
exchange is being routed. The stop shuts the
+ * consumer threads down, which interrupts a thread that still waits for its 
exchange: the transaction must not be
+ * rolled back while the exchange goes on and completes, or its message is 
consumed again.
+ */
+class HazelcastSedaTransactedStopTest extends CamelTestSupport {
+
+    private final CountDownLatch release = new CountDownLatch(1);
+    private final AtomicInteger started = new AtomicInteger();
+    private final AtomicInteger completed = new AtomicInteger();
+    private final AtomicLong selfStopMillis = new AtomicLong(-1);
+    private final AtomicBoolean failNextConsumerExchange = new AtomicBoolean();
+    private final ExecutorService stopper = 
Executors.newSingleThreadExecutor();
+    private HazelcastInstance member;
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        Config config = new Config();
+        config.setClusterName("seda-transacted-stop-" + UUID.randomUUID());
+        config.getMetricsConfig().setEnabled(false);
+        
config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
+        
config.getNetworkConfig().getJoin().getAutoDetectionConfig().setEnabled(false);
+        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
+        member = Hazelcast.newHazelcastInstance(config);
+        CamelContext context = super.createCamelContext();
+        context.getCamelContextExtension().setExchangeFactory(new 
FailingExchangeFactory(null, failNextConsumerExchange));
+        context.getRegistry().bind("hazelcastInstance", member);
+        // the time a graceful shutdown of a thread pool waits before it 
interrupts the threads (10 s by default, which
+        // is less than the 45 s that the shutdown strategy waits for the 
exchanges in flight), scaled down for the test
+        context.getExecutorServiceManager().setShutdownAwaitTermination(1000);
+        return context;
+    }
+
+    @AfterEach
+    void shutdownMember() {
+        release.countDown();
+        // stop the routes before the member, so the consumers do not poll a 
member that is shut down
+        context.stop();
+        stopper.shutdownNow();
+        if (member != null) {
+            member.shutdown();
+        }
+    }
+
+    @Test
+    void exchangeThatContinuesOnAnotherThreadIsCommittedWhenTheRouteStops() 
throws Exception {
+        stopWhileAnExchangeIsRouted("async");
+    }
+
+    @Test
+    void synchronousExchangeIsCommittedWhenTheRouteStops() throws Exception {
+        stopWhileAnExchangeIsRouted("sync");
+    }
+
+    @Test
+    void exchangeThatOutlastsTheShutdownTimeoutIsRolledBack() throws Exception 
{
+        // control (as before the fix): the stop waits at most the shutdown 
timeout, and then rolls back the exchange
+        context.getShutdownStrategy().setTimeout(2);
+        IQueue<Object> queue = member.getQueue("async");
+        queue.offer("a");
+        context.getRouteController().startRoute("async");
+        await().atMost(10, TimeUnit.SECONDS).until(() -> started.get() == 1);
+
+        long start = System.nanoTime();
+        context.getRouteController().stopRoute("async");
+        long stopMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - 
start);
+
+        assertTrue(stopMillis < 8000, "Stopping the route took " + stopMillis 
+ " ms");
+        await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> 
assertEquals(1, queue.size(),
+                "The exchange that was still routed when the shutdown timed 
out was not rolled back"));
+        assertEquals(0, completed.get());
+    }
+
+    @Test
+    void forcedShutdownDoesNotWaitForTheExchangeAgain() throws Exception {
+        // the route is deferred, so the shutdown strategy waits for its 
exchange before it stops the consumer: when it
+        // times out, it stops the consumer at once (forced), and the consumer 
must not wait another shutdown timeout
+        context.getShutdownStrategy().setTimeout(4);
+        IQueue<Object> queue = member.getQueue("deferred");
+        queue.offer("a");
+        context.getRouteController().startRoute("deferred");
+        await().atMost(10, TimeUnit.SECONDS).until(() -> started.get() == 1);
+
+        long start = System.nanoTime();
+        context.getRouteController().stopRoute("deferred");
+        long stopMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - 
start);
+
+        // 4 s of the shutdown strategy and 1 s of shutdownAwaitTermination; 
another 4 s when the consumer waits again
+        assertTrue(stopMillis < 7000, "Stopping the route took " + stopMillis 
+ " ms");
+        await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> 
assertEquals(1, queue.size(),
+                "The exchange that was still routed when the shutdown timed 
out was not rolled back"));
+        assertEquals(0, completed.get());
+    }
+
+    @Test
+    void consumerStoppedByARoutePolicyOfItsOwnExchangeDoesNotWaitForIt() 
throws Exception {
+        // a route policy stops the consumer when its exchange completes, on 
the consumer thread of that exchange,
+        // which cannot end its exchange while the stop waits for it
+        context.getShutdownStrategy().setTimeout(6);
+        member.getQueue("selfstop").offer("a");
+        context.getRouteController().startRoute("selfstop");
+
+        await().atMost(20, TimeUnit.SECONDS).until(() -> selfStopMillis.get() 
>= 0);
+        assertTrue(selfStopMillis.get() < 4000, "Stopping the consumer took " 
+ selfStopMillis.get() + " ms");
+    }
+
+    @Test
+    void exchangeThatCannotBeCreatedDoesNotHoldUpTheStop() throws Exception {
+        // the consumer thread fails to create its exchange and ends: the stop 
must not wait for it as if it routed one
+        context.getShutdownStrategy().setTimeout(6);
+        failNextConsumerExchange.set(true);
+        context.getRouteController().startRoute("sync");
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
!failNextConsumerExchange.get());
+
+        long start = System.nanoTime();
+        context.getRouteController().stopRoute("sync");
+        long stopMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - 
start);
+
+        assertTrue(stopMillis < 4000, "Stopping the route took " + stopMillis 
+ " ms");
+        assertEquals(0, started.get());
+    }
+
+    private void stopWhileAnExchangeIsRouted(String routeId) throws Exception {
+        IQueue<Object> queue = member.getQueue(routeId);
+        queue.offer("a");
+        context.getRouteController().startRoute(routeId);
+        await().atMost(10, TimeUnit.SECONDS).until(() -> started.get() == 1);
+
+        Future<?> stop = stopper.submit(() -> {
+            context.getRouteController().stopRoute(routeId);
+            return null;
+        });
+
+        // longer than the shutdownAwaitTermination of 1 s, after which the 
consumer thread was interrupted: its
+        // transaction was rolled back (the message back in the queue) while 
the exchange went on
+        await().during(3, TimeUnit.SECONDS).atMost(5, 
TimeUnit.SECONDS).untilAsserted(() -> {
+            assertEquals(0, queue.size(), "The transaction was rolled back 
while the exchange was routed");
+            assertFalse(stop.isDone(), "The stop did not wait for the 
exchange");
+        });
+
+        release.countDown();
+        stop.get(20, TimeUnit.SECONDS);
+        assertEquals(1, completed.get());
+        assertEquals(0, queue.size(), "The completed exchange was rolled 
back");
+
+        // the next start does not consume the message again
+        context.getRouteController().startRoute(routeId);
+        await().during(2, TimeUnit.SECONDS).atMost(5, TimeUnit.SECONDS)
+                .untilAsserted(() -> assertEquals(1, started.get(), "The 
message was consumed again"));
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from("hazelcast-seda:async?transacted=true&hazelcastInstance=#hazelcastInstance").routeId("async")
+                        .autoStartup(false)
+                        .threads(1)
+                        .process(exchange -> routeStep());
+
+                
from("hazelcast-seda:sync?transacted=true&hazelcastInstance=#hazelcastInstance").routeId("sync")
+                        .autoStartup(false)
+                        .process(exchange -> routeStep());
+
+                
from("hazelcast-seda:deferred?transacted=true&hazelcastInstance=#hazelcastInstance").routeId("deferred")
+                        .autoStartup(false)
+                        .shutdownRoute(ShutdownRoute.Defer)
+                        .process(exchange -> routeStep());
+
+                
from("hazelcast-seda:selfstop?transacted=true&hazelcastInstance=#hazelcastInstance").routeId("selfstop")
+                        .autoStartup(false)
+                        .routePolicy(new RoutePolicySupport() {
+                            @Override
+                            public void onExchangeDone(Route route, Exchange 
exchange) {
+                                if (selfStopMillis.get() < 0) {
+                                    long start = System.nanoTime();
+                                    try {
+                                        stopConsumer(route.getConsumer());
+                                    } catch (Exception e) {
+                                        throw new IllegalStateException(e);
+                                    } finally {
+                                        
selfStopMillis.set(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start));
+                                    }
+                                }
+                            }
+                        })
+                        .log("${body}");
+            }
+        };
+    }
+
+    /**
+     * Fails the creation of the next exchange of a consumer when asked to.
+     */
+    private static final class FailingExchangeFactory extends 
PrototypeExchangeFactory {
+
+        private final AtomicBoolean failNext;
+
+        FailingExchangeFactory(Consumer consumer, AtomicBoolean failNext) {
+            super(consumer);
+            this.failNext = failNext;
+        }
+
+        @Override
+        public ExchangeFactory newExchangeFactory(Consumer consumer) {
+            FailingExchangeFactory answer = new 
FailingExchangeFactory(consumer, failNext);
+            answer.setCamelContext(getCamelContext());
+            return answer;
+        }
+
+        @Override
+        public Exchange create(Endpoint fromEndpoint, boolean autoRelease) {
+            if (getConsumer() != null && failNext.compareAndSet(true, false)) {
+                throw new IllegalStateException("Simulated failure to create 
the exchange");
+            }
+            return super.create(fromEndpoint, autoRelease);
+        }
+    }
+
+    private void routeStep() throws InterruptedException {
+        started.incrementAndGet();
+        if (!release.await(30, TimeUnit.SECONDS)) {
+            throw new IllegalStateException("The test did not release the 
exchange");
+        }
+        completed.incrementAndGet();
+    }
+}

Reply via email to