This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch CAMEL-27499-threads-shutdown-pool
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 24ce4590236f9ee84b9aec42f3e61c4b9e9b9774
Author: Claus Ibsen <[email protected]>
AuthorDate: Wed Nov 25 15:54:11 2026 +0100

    CAMEL-27499, CAMEL-27501: camel-core - Threads and Wire Tap EIP: a thread 
pool that is shut down no longer drops the task silently
    
    With the CallerRuns policy (the default), a thread pool that is shut
    down neither ran a new task nor threw. The Threads EIP never completed
    the exchange (its caller waited for ever), and the Wire Tap lost the
    tap and kept it counted as pending, so a graceful stop of the route
    waited for its full timeout.
    
    The CallerRuns policy now rejects a Rejectable task of a shut down
    pool, as Abort and Block already did; a plain task is still dropped,
    as with ThreadPoolExecutor.CallerRunsPolicy. The Block policy takes a
    task out again when the pool was shut down while it waited for queue
    space (as ThreadPoolExecutor.execute does). The task of the Wire Tap
    is Rejectable: a rejection fails the exchange with a
    RejectedExecutionException, as with the Abort policy before.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    Signed-off-by: Claus Ibsen <[email protected]>
---
 .../apache/camel/processor/WireTapProcessor.java   |  14 +-
 .../camel/processor/ThreadsShutDownPoolTest.java   |  94 +++++++++++++
 .../camel/processor/WireTapShutDownPoolTest.java   |  76 +++++++++++
 .../util/concurrent/ThreadPoolRejectedPolicy.java  |  26 +++-
 .../concurrent/ThreadPoolRejectedPolicyTest.java   | 151 +++++++++++++++++++++
 .../modules/ROOT/pages/threading-model.adoc        |   5 +
 6 files changed, 364 insertions(+), 2 deletions(-)

diff --git 
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/WireTapProcessor.java
 
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/WireTapProcessor.java
index 9f41f0fd3f17..679f3dcbe739 100644
--- 
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/WireTapProcessor.java
+++ 
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/WireTapProcessor.java
@@ -19,6 +19,7 @@ package org.apache.camel.processor;
 import java.io.IOException;
 import java.util.List;
 import java.util.concurrent.ExecutorService;
+import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.atomic.LongAdder;
 
 import org.apache.camel.AsyncCallback;
@@ -44,6 +45,7 @@ import org.apache.camel.spi.StepIdAware;
 import org.apache.camel.support.AsyncProcessorConverterHelper;
 import org.apache.camel.support.service.ServiceHelper;
 import org.apache.camel.util.ObjectHelper;
+import org.apache.camel.util.concurrent.Rejectable;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -86,7 +88,7 @@ public class WireTapProcessor extends BaseProcessorSupport
         this.dynamicUri = dynamicUri;
     }
 
-    private final class WireTapTask implements PooledExchangeTask {
+    private final class WireTapTask implements PooledExchangeTask, Rejectable {
 
         private Exchange exchange;
         private final AsyncCallback callback = new AsyncCallback() {
@@ -116,6 +118,16 @@ public class WireTapProcessor extends BaseProcessorSupport
             LOG.debug(">>>> (wiretap) {} {}", uri, exchange);
             asyncProcessor.process(exchange, callback);
         }
+
+        @Override
+        public void reject() {
+            // the thread pool rejects the task, also when it is shut down 
(where the CallerRuns policy does not run
+            // it): fail the submit, so process takes the task off the pending 
count and the error handler can react,
+            // as with the Abort policy
+            throw new RejectedExecutionException(
+                    "The thread pool of the Wire Tap " + id + 
(executorService.isShutdown() ? " is shut down" : " is full")
+                                                 + ": the tapped exchange is 
not sent to " + uri);
+        }
     }
 
     @Override
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/processor/ThreadsShutDownPoolTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/processor/ThreadsShutDownPoolTest.java
new file mode 100644
index 000000000000..2f4ad4bbc821
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/processor/ThreadsShutDownPoolTest.java
@@ -0,0 +1,94 @@
+/*
+ * 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.processor;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+
+/**
+ * The Threads EIP with a thread pool that its owner shut down: the exchange 
must fail with a
+ * {@link RejectedExecutionException}, instead of never being completed.
+ */
+class ThreadsShutDownPoolTest extends ContextTestSupport {
+
+    private ExecutorService camelPool;
+    private ExecutorService jdkPool;
+
+    @Test
+    void testCamelThreadPoolShutDown() throws Exception {
+        // a thread pool of Camel, with the CallerRuns policy
+        camelPool.shutdown();
+        assertRejected("direct:camel");
+    }
+
+    @Test
+    void testJdkThreadPoolShutDown() throws Exception {
+        // a thread pool of the JDK, with the AbortPolicy: the CallerRuns 
policy of the EIP takes over
+        jdkPool.shutdown();
+        assertRejected("direct:jdk");
+    }
+
+    private void assertRejected(String uri) throws Exception {
+        getMockEndpoint("mock:result").expectedMessageCount(0);
+
+        Future<Exchange> future = template.asyncSend(uri, e -> 
e.getIn().setBody("Hello"));
+        Exchange exchange = future.get(10, TimeUnit.SECONDS);
+
+        assertInstanceOf(RejectedExecutionException.class, 
exchange.getException());
+        assertMockEndpointsSatisfied();
+        assertEquals(0, context.getInflightRepository().size());
+    }
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext context = super.createCamelContext();
+        camelPool = 
context.getExecutorServiceManager().newDefaultThreadPool(this, "shared");
+        jdkPool = Executors.newFixedThreadPool(1);
+        context.getRegistry().bind("camelPool", camelPool);
+        context.getRegistry().bind("jdkPool", jdkPool);
+        return context;
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        super.tearDown();
+        jdkPool.shutdownNow();
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from("direct:camel").threads().executorService("camelPool").to("mock:result");
+                
from("direct:jdk").threads().executorService("jdkPool").to("mock:result");
+            }
+        };
+    }
+}
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/processor/WireTapShutDownPoolTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/processor/WireTapShutDownPoolTest.java
new file mode 100644
index 000000000000..67176fb216b0
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/processor/WireTapShutDownPoolTest.java
@@ -0,0 +1,76 @@
+/*
+ * 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.processor;
+
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.RejectedExecutionException;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+
+/**
+ * The Wire Tap EIP with a thread pool that its owner shut down (with the 
default CallerRuns policy): the taps that
+ * cannot be sent must not be lost silently, nor stay counted as pending 
exchanges, as a graceful shutdown of the route
+ * would wait for them until its timeout.
+ */
+class WireTapShutDownPoolTest extends ContextTestSupport {
+
+    private ExecutorService pool;
+
+    @Test
+    void testThreadPoolShutDown() throws Exception {
+        pool.shutdown();
+
+        getMockEndpoint("mock:main").expectedMessageCount(0);
+        getMockEndpoint("mock:tapped").expectedMessageCount(0);
+
+        // the tap is rejected, as with the Abort policy: the exchange fails, 
so the error handler can react
+        for (String body : List.of("A", "B", "C")) {
+            Exchange exchange = template.send("direct:start", e -> 
e.getIn().setBody(body));
+            assertInstanceOf(RejectedExecutionException.class, 
exchange.getException());
+        }
+
+        assertMockEndpointsSatisfied();
+        WireTapProcessor tap = context.getProcessor("tap", 
WireTapProcessor.class);
+        assertEquals(0, tap.getPendingExchangesSize());
+    }
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext context = super.createCamelContext();
+        pool = context.getExecutorServiceManager().newDefaultThreadPool(this, 
"shared");
+        context.getRegistry().bind("sharedPool", pool);
+        return context;
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from("direct:start").wireTap("mock:tapped").executorService("sharedPool").id("tap").to("mock:main");
+            }
+        };
+    }
+}
diff --git 
a/core/camel-util/src/main/java/org/apache/camel/util/concurrent/ThreadPoolRejectedPolicy.java
 
b/core/camel-util/src/main/java/org/apache/camel/util/concurrent/ThreadPoolRejectedPolicy.java
index 2b9cecacbe06..c8468f13205e 100644
--- 
a/core/camel-util/src/main/java/org/apache/camel/util/concurrent/ThreadPoolRejectedPolicy.java
+++ 
b/core/camel-util/src/main/java/org/apache/camel/util/concurrent/ThreadPoolRejectedPolicy.java
@@ -53,6 +53,19 @@ public enum ThreadPoolRejectedPolicy {
             };
         } else if (this == CallerRuns) {
             return new ThreadPoolExecutor.CallerRunsPolicy() {
+                @Override
+                public void rejectedExecution(Runnable r, ThreadPoolExecutor 
executor) {
+                    if (executor.isShutdown()) {
+                        // the caller does not run the task of a shut down 
pool: a rejectable task is rejected, so its
+                        // exchange is completed, instead of being dropped 
without notice
+                        if (r instanceof Rejectable rejectable) {
+                            rejectable.reject();
+                        }
+                    } else {
+                        r.run();
+                    }
+                }
+
                 @Override
                 public String toString() {
                     return "CallerRuns";
@@ -69,7 +82,18 @@ public enum ThreadPoolRejectedPolicy {
                             Thread.currentThread().interrupt();
                             throw new RejectedExecutionException("Interrupted 
while waiting for queue space", e);
                         }
-                    } else if (r instanceof Rejectable rejectable) {
+                        // a shutdownNow while waiting drains the queue, which 
makes space for the task in a pool that
+                        // no longer runs it: take it out again, as 
ThreadPoolExecutor.execute does
+                        if (executor.isShutdown() && executor.remove(r)) {
+                            reject(r, executor);
+                        }
+                    } else {
+                        reject(r, executor);
+                    }
+                }
+
+                private void reject(Runnable r, ThreadPoolExecutor executor) {
+                    if (r instanceof Rejectable rejectable) {
                         // the task cannot run as the pool is shutdown
                         rejectable.reject();
                     } else {
diff --git 
a/core/camel-util/src/test/java/org/apache/camel/util/concurrent/ThreadPoolRejectedPolicyTest.java
 
b/core/camel-util/src/test/java/org/apache/camel/util/concurrent/ThreadPoolRejectedPolicyTest.java
new file mode 100644
index 000000000000..2d84fff1f41f
--- /dev/null
+++ 
b/core/camel-util/src/test/java/org/apache/camel/util/concurrent/ThreadPoolRejectedPolicyTest.java
@@ -0,0 +1,151 @@
+/*
+ * 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.util.concurrent;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+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;
+
+/**
+ * The rejected policies with a thread pool that is shut down: a {@link 
Rejectable} task must be rejected, not dropped
+ * without notice.
+ */
+class ThreadPoolRejectedPolicyTest {
+
+    @Test
+    void testCallerRunsRejectsARejectableTaskOfAShutDownPool() {
+        ThreadPoolExecutor pool = newPool(ThreadPoolRejectedPolicy.CallerRuns, 
10);
+        pool.shutdown();
+
+        CountingTask task = new CountingTask();
+        pool.execute(task);
+
+        assertEquals(0, task.runs.get());
+        assertEquals(1, task.rejects.get());
+    }
+
+    @Test
+    void testCallerRunsRejectsARejectableTaskSubmittedToAShutDownPool() {
+        ThreadPoolExecutor pool = newPool(ThreadPoolRejectedPolicy.CallerRuns, 
10);
+        pool.shutdown();
+
+        // submit wraps the task in a RejectableFutureTask, which hands the 
rejection on
+        CountingTask task = new CountingTask();
+        pool.submit(task);
+
+        assertEquals(0, task.runs.get());
+        assertEquals(1, task.rejects.get());
+    }
+
+    @Test
+    void testCallerRunsDropsAPlainTaskOfAShutDownPool() {
+        ThreadPoolExecutor pool = newPool(ThreadPoolRejectedPolicy.CallerRuns, 
10);
+        pool.shutdown();
+
+        // as ThreadPoolExecutor.CallerRunsPolicy: no exception, the task does 
not run
+        AtomicInteger runs = new AtomicInteger();
+        pool.execute(runs::incrementAndGet);
+
+        assertEquals(0, runs.get());
+    }
+
+    @Test
+    void testCallerRunsRunsTheTaskInTheCallerWhenThePoolIsFull() throws 
Exception {
+        CountDownLatch release = new CountDownLatch(1);
+        ThreadPoolExecutor pool = newPool(ThreadPoolRejectedPolicy.CallerRuns, 
1);
+        try {
+            pool.execute(() -> awaitQuietly(release));
+            pool.execute(() -> awaitQuietly(release));
+
+            CountingTask task = new CountingTask();
+            pool.execute(task);
+
+            assertEquals(Thread.currentThread(), task.thread);
+            assertEquals(1, task.runs.get());
+            assertEquals(0, task.rejects.get());
+        } finally {
+            release.countDown();
+            pool.shutdownNow();
+        }
+    }
+
+    @Test
+    void testBlockRejectsATaskPutIntoAPoolShutDownWhileWaiting() throws 
Exception {
+        CountDownLatch release = new CountDownLatch(1);
+        ThreadPoolExecutor pool = newPool(ThreadPoolRejectedPolicy.Block, 1);
+        try {
+            // one task runs, one fills the queue
+            pool.execute(() -> awaitQuietly(release));
+            pool.execute(() -> awaitQuietly(release));
+
+            CountingTask task = new CountingTask();
+            Thread caller = new Thread(() -> pool.execute(task));
+            caller.start();
+            await().atMost(10, TimeUnit.SECONDS).until(() -> caller.getState() 
== Thread.State.WAITING);
+
+            // shutdownNow drains the queue: the waiting caller gets the 
space, but the pool no longer runs the task
+            pool.shutdownNow();
+            caller.join(10000);
+            assertFalse(caller.isAlive());
+
+            assertEquals(0, task.runs.get());
+            assertEquals(1, task.rejects.get());
+            assertTrue(pool.getQueue().isEmpty());
+        } finally {
+            release.countDown();
+        }
+    }
+
+    private static ThreadPoolExecutor newPool(ThreadPoolRejectedPolicy policy, 
int queueSize) {
+        return new RejectableThreadPoolExecutor(
+                1, 1, 60, TimeUnit.SECONDS, new 
LinkedBlockingQueue<>(queueSize), policy.asRejectedExecutionHandler());
+    }
+
+    private static void awaitQuietly(CountDownLatch latch) {
+        try {
+            latch.await(20, TimeUnit.SECONDS);
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+        }
+    }
+
+    private static final class CountingTask implements Runnable, Rejectable {
+        final AtomicInteger runs = new AtomicInteger();
+        final AtomicInteger rejects = new AtomicInteger();
+        volatile Thread thread;
+
+        @Override
+        public void run() {
+            thread = Thread.currentThread();
+            runs.incrementAndGet();
+        }
+
+        @Override
+        public void reject() {
+            rejects.incrementAndGet();
+        }
+    }
+}
diff --git a/docs/user-manual/modules/ROOT/pages/threading-model.adoc 
b/docs/user-manual/modules/ROOT/pages/threading-model.adoc
index 138ed02e480c..69a0d875fb55 100644
--- a/docs/user-manual/modules/ROOT/pages/threading-model.adoc
+++ b/docs/user-manual/modules/ROOT/pages/threading-model.adoc
@@ -332,6 +332,11 @@ systems where failing fast is preferred over blocking.
 message broker consumers and batch workloads where losing a task is 
unacceptable and latency is less critical.
 |===
 
+A thread pool that is shut down runs no new task, whatever the policy. This 
happens when a route uses a thread pool
+that is shut down by its owner (for example a shared pool), or when the route 
is removed. The EIPs then do not lose the
+task silently: the xref:components:eips:threads-eip.adoc[Threads] and 
xref:components:eips:wireTap-eip.adoc[Wire Tap]
+EIPs fail the exchange with a `RejectedExecutionException`, as with the 
`Abort` policy, so the error handler can react.
+
 With virtual threads, a task of the pool that submits more work to the same 
pool runs it at once when no permit is
 free, whatever the policy, instead of waiting (see <<virtual-threads>>).
 

Reply via email to