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 12014575a8f2 CAMEL-26909: camel-core - an Error of the supplier of a 
BackgroundTask no longer leaves run() waiting forever (#29900)
12014575a8f2 is described below

commit 12014575a8f2c71174a8f9f4cbef9a61e25439e8
Author: allthingssecurity <[email protected]>
AuthorDate: Mon Nov 16 15:50:11 2026 +0530

    CAMEL-26909: camel-core - an Error of the supplier of a BackgroundTask no 
longer leaves run() waiting forever (#29900)
    
    BackgroundTask runs its supplier from a task scheduled with 
scheduleWithFixedDelay. Since
    CAMEL-24286 an exception of the supplier marks the task failed, unregisters 
it and releases the
    caller of run(). An Error that is not a VirtualMachineError (such as a 
NoClassDefFoundError of a
    client library) was not caught there: it ended the schedule, a run() with 
an unlimited duration
    waited forever, and the task stayed Active in the TaskManagerRegistry.
    
    runTaskWrapper now handles such an Error as an exception: the task is 
Failed with it as its
    cause, run() returns false, and the task is unregistered; the Error is 
logged at WARN and thrown
    on, which ends the schedule. A VirtualMachineError is left as before.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../task/task/BackgroundTaskRegistryTest.java      | 55 +++++++++++++++++++++-
 .../apache/camel/support/task/BackgroundTask.java  | 11 ++++-
 2 files changed, 63 insertions(+), 3 deletions(-)

diff --git 
a/core/camel-core/src/test/java/org/apache/camel/support/task/task/BackgroundTaskRegistryTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/support/task/task/BackgroundTaskRegistryTest.java
index 011228af1275..b8a77c7d4a14 100644
--- 
a/core/camel-core/src/test/java/org/apache/camel/support/task/task/BackgroundTaskRegistryTest.java
+++ 
b/core/camel-core/src/test/java/org/apache/camel/support/task/task/BackgroundTaskRegistryTest.java
@@ -19,6 +19,7 @@ package org.apache.camel.support.task.task;
 import java.time.Duration;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 
@@ -26,6 +27,7 @@ import org.apache.camel.CamelContext;
 import org.apache.camel.impl.DefaultCamelContext;
 import org.apache.camel.support.PluginHelper;
 import org.apache.camel.support.task.BackgroundTask;
+import org.apache.camel.support.task.Task;
 import org.apache.camel.support.task.TaskManagerRegistry;
 import org.apache.camel.support.task.Tasks;
 import org.apache.camel.support.task.budget.Budgets;
@@ -132,13 +134,56 @@ class BackgroundTaskRegistryTest {
     @Test
     @Timeout(15)
     void testRunReturnsAndUnregistersWhenSupplierThrows() throws Exception {
+        assertRunReturnsAndUnregistersWhenSupplierThrows(new 
IllegalStateException("boom"));
+    }
+
+    @DisplayName("Test that run() returns and unregisters when the supplier 
throws an Error")
+    @Test
+    @Timeout(15)
+    void testRunReturnsAndUnregistersWhenSupplierThrowsAnError() throws 
Exception {
+        // such as a NoClassDefFoundError of a client library: before, the 
Error ended the schedule, and run() blocked
+        // forever
+        assertRunReturnsAndUnregistersWhenSupplierThrows(new 
NoClassDefFoundError("boom"));
+    }
+
+    @DisplayName("Test that a scheduled task fails and unregisters when the 
supplier throws an Error")
+    @Test
+    @Timeout(15)
+    void testScheduledTaskFailsAndUnregistersWhenSupplierThrowsAnError() {
+        ScheduledExecutorService executor = 
Executors.newSingleThreadScheduledExecutor();
+        try {
+            BackgroundTask task = Tasks.backgroundTask()
+                    .withScheduledExecutor(executor)
+                    .withBudget(Budgets.iterationTimeBudget()
+                            .withInterval(Duration.ofMillis(100))
+                            .withInitialDelay(Duration.ZERO)
+                            .withUnlimitedDuration()
+                            .build())
+                    .build();
+            NoClassDefFoundError error = new NoClassDefFoundError("boom");
+            task.schedule(camelContext, () -> {
+                throw error;
+            });
+            // before, the status stayed Active and the task stayed in the 
registry
+            await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
+                assertThat(task.getStatus()).isEqualTo(Task.Status.Failed);
+                assertThat(task.getException()).isSameAs(error);
+                assertThat(registry.getTasks()).isEmpty();
+            });
+        } finally {
+            executor.shutdownNow();
+        }
+    }
+
+    private void assertRunReturnsAndUnregistersWhenSupplierThrows(Throwable 
failure) throws Exception {
         AtomicBoolean runReturned = new AtomicBoolean(false);
         AtomicBoolean completed = new AtomicBoolean(true);
 
         // an unlimited-duration task: before CAMEL-24286 a thrown supplier 
exception left the latch
         // un-counted, so run() blocked forever here and the task leaked in 
the registry
+        ScheduledExecutorService executor = 
Executors.newSingleThreadScheduledExecutor();
         BackgroundTask task = Tasks.backgroundTask()
-                
.withScheduledExecutor(Executors.newSingleThreadScheduledExecutor())
+                .withScheduledExecutor(executor)
                 .withBudget(Budgets.iterationTimeBudget()
                         .withInterval(Duration.ofMillis(100))
                         .withInitialDelay(Duration.ZERO)
@@ -149,7 +194,10 @@ class BackgroundTaskRegistryTest {
         // daemon so a regression (run() hanging forever) cannot keep the JVM 
alive
         Thread runner = new Thread(() -> {
             boolean result = task.run(camelContext, () -> {
-                throw new IllegalStateException("boom");
+                if (failure instanceof Error error) {
+                    throw error;
+                }
+                throw (RuntimeException) failure;
             });
             completed.set(result);
             runReturned.set(true);
@@ -169,6 +217,9 @@ class BackgroundTaskRegistryTest {
                 .untilAsserted(() -> assertThat(registry.getTasks())
                         .as("the failed task must not leak in the registry")
                         .isEmpty());
+        assertThat(task.getStatus()).isEqualTo(Task.Status.Failed);
+        assertThat(task.getException()).isSameAs(failure);
+        executor.shutdownNow();
     }
 
     @DisplayName("Test that task is removed from registry after supplier 
succeeds")
diff --git 
a/core/camel-support/src/main/java/org/apache/camel/support/task/BackgroundTask.java
 
b/core/camel-support/src/main/java/org/apache/camel/support/task/BackgroundTask.java
index 16051c76775e..70391a0c7f23 100644
--- 
a/core/camel-support/src/main/java/org/apache/camel/support/task/BackgroundTask.java
+++ 
b/core/camel-support/src/main/java/org/apache/camel/support/task/BackgroundTask.java
@@ -144,7 +144,16 @@ public class BackgroundTask extends AbstractTask 
implements BlockingTask {
                 unschedule(false);
                 LOG.trace("Task {} succeeded and the current task is 
unscheduled: {}", getName(), latch.getCount());
             }
-        } catch (Exception e) {
+        } catch (VirtualMachineError e) {
+            // left as before: thrown on, without releasing the caller of run()
+            throw e;
+        } catch (Exception | Error e) {
+            // also an Error (such as a NoClassDefFoundError of a client 
library the supplier connects with), which would
+            // otherwise end the schedule without releasing the caller
+            if (e instanceof Error) {
+                // nothing reads the Future it is thrown on to, and the task 
leaves the registry here: log it once
+                LOG.warn("Task {} failed with an error and is not attempted 
again: {}", getName(), e, e);
+            }
             status = Status.Failed;
             completed.set(false);
             cause = e;

Reply via email to