This is an automated email from the ASF dual-hosted git repository.
Croway 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 136c5c69d27c CAMEL-27515: camel-timer - follow-up of CAMEL-27470
(#30721)
136c5c69d27c is described below
commit 136c5c69d27ceede51cdfb147fb9cd38314f4b44
Author: Federico Mariani <[email protected]>
AuthorDate: Tue Nov 24 16:18:28 2026 +0100
CAMEL-27515: camel-timer - follow-up of CAMEL-27470 (#30721)
- sendTimerExchange: no longer release the exchange when an Error escapes
the
route. Releasing does not remove it from the inflight repository, and
with the
pooled exchange factory it reset an exchange that the route can still use
(CAMEL-27515). TimerPooledExchangeVirtualMachineErrorTest covers it.
- Name the route id in the fatal ERROR line: routes can share a timer uri.
- TimerNegativeDelayVirtualMachineErrorTest asserts the ERROR line, so it
fails
without the catch of the executor path.
- TimerVirtualMachineErrorTest asserts that the failed route stops firing
while
the other route keeps firing, and fires again once restarted.
---
.../camel/component/timer/TimerConsumer.java | 28 +++----
.../TimerNegativeDelayVirtualMachineErrorTest.java | 86 ++++++++++++++++++----
...TimerPooledExchangeVirtualMachineErrorTest.java | 83 +++++++++++++++++++++
.../timer/TimerVirtualMachineErrorTest.java | 27 ++++++-
4 files changed, 192 insertions(+), 32 deletions(-)
diff --git
a/components/camel-timer/src/main/java/org/apache/camel/component/timer/TimerConsumer.java
b/components/camel-timer/src/main/java/org/apache/camel/component/timer/TimerConsumer.java
index d57b10d1d492..882c947f679c 100644
---
a/components/camel-timer/src/main/java/org/apache/camel/component/timer/TimerConsumer.java
+++
b/components/camel-timer/src/main/java/org/apache/camel/component/timer/TimerConsumer.java
@@ -150,11 +150,12 @@ public class TimerConsumer extends DefaultConsumer
implements StartupListener, S
// trouble, but allowing the error to propagate would
additionally kill sibling
// routes, which is strictly worse.
cancel();
+ // the route id says which route to restart, as routes
can share the same timer uri
LOG.error(
- "Fatal error processing exchange on timer: {}."
+ "Fatal error processing exchange on route: {}
from timer: {}."
+ " The timer task for this route has been
cancelled."
+ " The route no longer fires until it is
restarted.",
- endpoint, t);
+ getRouteId(), endpoint, t);
} finally {
polling = false;
}
@@ -220,10 +221,10 @@ public class TimerConsumer extends DefaultConsumer
implements StartupListener, S
// An Error (such as StackOverflowError) must not be
silently swallowed in the executor
// path. Log at ERROR so the operator sees it.
LOG.error(
- "Fatal error processing exchange on timer: {}."
+ "Fatal error processing exchange on route: {} from
timer: {}."
+ " The timer task for this route has been
terminated."
+ " The route no longer fires until it is
restarted.",
- endpoint, t);
+ getRouteId(), endpoint, t);
} finally {
polling = false;
}
@@ -324,17 +325,16 @@ public class TimerConsumer extends DefaultConsumer
implements StartupListener, S
AsyncCallback cb = defaultConsumerCallback(exchange, false);
getAsyncProcessor().process(exchange, cb);
} else {
- // Use an outer try-finally so that releaseExchange is always
called,
- // even if an Error (e.g. StackOverflowError) escapes
getProcessor().process().
- // Without this, an Error would leave the exchange inflight and
cause
- // the context shutdown to wait for the full shutdown timeout.
+ // an Error that escapes process(...) skips the release on
purpose: the route may still use the exchange
+ // (CAMEL-27515), and releasing it would not remove it from the
inflight repository anyway
+ try {
+ getProcessor().process(exchange);
+ } catch (Exception e) {
+ exchange.setException(e);
+ }
+
+ // handle any thrown exception
try {
- try {
- getProcessor().process(exchange);
- } catch (Exception e) {
- exchange.setException(e);
- }
- // handle any thrown exception
if (exchange.getException() != null) {
getExceptionHandler().handleException("Error processing
exchange", exchange, exchange.getException());
}
diff --git
a/core/camel-core/src/test/java/org/apache/camel/component/timer/TimerNegativeDelayVirtualMachineErrorTest.java
b/core/camel-core/src/test/java/org/apache/camel/component/timer/TimerNegativeDelayVirtualMachineErrorTest.java
index b5bb7d4ef1f5..9b97ca5397d9 100644
---
a/core/camel-core/src/test/java/org/apache/camel/component/timer/TimerNegativeDelayVirtualMachineErrorTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/component/timer/TimerNegativeDelayVirtualMachineErrorTest.java
@@ -16,34 +16,90 @@
*/
package org.apache.camel.component.timer;
-import java.util.concurrent.CountDownLatch;
+import java.time.Duration;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.config.Property;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
- * Verifies that a VirtualMachineError (StackOverflowError) thrown in a timer
route with a negative delay (executor
- * path) is caught and logged, and that the route's fire loop terminates
rather than propagating the error.
+ * A VirtualMachineError (StackOverflowError) thrown in a timer route with a
negative delay (executor path) ends the
+ * fire loop of the route, and the consumer logs it at ERROR with the route to
restart.
*
* @see <a
href="https://issues.apache.org/jira/browse/CAMEL-27470">CAMEL-27470</a>
*/
class TimerNegativeDelayVirtualMachineErrorTest extends ContextTestSupport {
- /** Open once route A has thrown its Error, confirming the error was
processed, not silently lost. */
- private final CountDownLatch errorThrown = new CountDownLatch(1);
+ private static final String ROUTE_ID = "route-neg-delay";
+
+ private final List<String> errors = new CopyOnWriteArrayList<>();
+ private final AtomicInteger fired = new AtomicInteger();
+ private AbstractAppender appender;
+
+ @BeforeEach
+ void captureErrors() {
+ appender = new AbstractAppender("timer-errors-" + UUID.randomUUID(),
null, null, true, Property.EMPTY_ARRAY) {
+ @Override
+ public void append(LogEvent event) {
+ String message = event.getMessage().getFormattedMessage();
+ // other tests run in parallel: keep only the lines of this
route
+ if
(event.getLoggerName().equals(TimerConsumer.class.getName()) &&
message.contains(ROUTE_ID)) {
+ errors.add(message);
+ }
+ }
+ };
+ appender.start();
+ LoggerContext logging = (LoggerContext) LogManager.getContext(false);
+ logging.getConfiguration().getRootLogger().addAppender(appender,
Level.ERROR, null);
+ logging.updateLoggers();
+ }
+
+ @AfterEach
+ void stopCapture() {
+ LoggerContext logging = (LoggerContext) LogManager.getContext(false);
+
logging.getConfiguration().getRootLogger().removeAppender(appender.getName());
+ logging.updateLoggers();
+ appender.stop();
+ }
@Test
- void negativeDelayRouteLoopTerminatesOnVirtualMachineError() throws
InterruptedException {
- // The executor path catches the Throwable: the loop must terminate
and the
- // latch must open. If the error propagated uncaught and killed the
thread,
- // the latch still opens because the lambda completes — so the main
assertion
- // is that this finishes in time (not that it hangs).
- boolean thrown = errorThrown.await(5, TimeUnit.SECONDS);
- assertTrue(thrown, "executor path must catch the StackOverflowError
and not hang");
+ void errorEndsTheLoopAndIsLogged() throws Exception {
+ // started here, once the appender is in place
+ context.getRouteController().startRoute(ROUTE_ID);
+
+ // without the catch of the executor path, the Error would go to the
uncaught exception handler of the thread,
+ // and the consumer would log nothing
+ await().atMost(10, TimeUnit.SECONDS).until(() -> !errors.isEmpty());
+ String error = errors.get(0);
+ assertTrue(error.contains("route: " + ROUTE_ID), error);
+ assertTrue(error.contains("The route no longer fires until it is
restarted."), error);
+
+ // the loop has ended: the route does not fire again
+ await().during(Duration.ofMillis(500)).atMost(2,
TimeUnit.SECONDS).until(() -> fired.get() == 1);
+ assertEquals(1, errors.size());
+ }
+
+ @Override
+ protected int getShutdownTimeout() {
+ // the exchange that failed with a VirtualMachineError stays inflight
(CAMEL-27515)
+ return 1;
}
@Override
@@ -51,10 +107,10 @@ class TimerNegativeDelayVirtualMachineErrorTest extends
ContextTestSupport {
return new RouteBuilder() {
@Override
public void configure() {
- from("timer:negDelay?delay=-1&period=0&synchronous=true")
- .routeId("route-neg-delay")
+ from("timer:negDelay?delay=-1&synchronous=true")
+ .routeId(ROUTE_ID).autoStartup(false)
.process(exchange -> {
- errorThrown.countDown();
+ fired.incrementAndGet();
throw new StackOverflowError("simulated
StackOverflowError in negative-delay route");
});
}
diff --git
a/core/camel-core/src/test/java/org/apache/camel/component/timer/TimerPooledExchangeVirtualMachineErrorTest.java
b/core/camel-core/src/test/java/org/apache/camel/component/timer/TimerPooledExchangeVirtualMachineErrorTest.java
new file mode 100644
index 000000000000..02565a8bfa0d
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/component/timer/TimerPooledExchangeVirtualMachineErrorTest.java
@@ -0,0 +1,83 @@
+/*
+ * 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.timer;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.engine.PooledExchangeFactory;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * With the pooled exchange factory, a timer route whose processor throws a
VirtualMachineError must not give the
+ * exchange back to the pool: the rest of the route may still run on it
(CAMEL-27515), and releasing it would reset it.
+ *
+ * @see <a
href="https://issues.apache.org/jira/browse/CAMEL-27515">CAMEL-27515</a>
+ */
+class TimerPooledExchangeVirtualMachineErrorTest extends ContextTestSupport {
+
+ private static final String ROUTE_ID = "route-pooled";
+
+ private final AtomicReference<Exchange> failed = new AtomicReference<>();
+
+ @Test
+ void exchangeIsNotReleasedAfterVirtualMachineError() {
+ TimerConsumer consumer = (TimerConsumer)
context.getRoute(ROUTE_ID).getConsumer();
+
+ // the timer task has ended once the processor has thrown and the
consumer is no longer polling
+ await().atMost(10, TimeUnit.SECONDS).until(() -> failed.get() != null
&& !consumer.isPolling());
+
+ // a released pooled exchange is reset, and would have lost its header
+ assertEquals("kept", failed.get().getMessage().getHeader("marker"));
+ }
+
+ @Override
+ protected CamelContext createCamelContext() throws Exception {
+ CamelContext camelContext = super.createCamelContext();
+ camelContext.getCamelContextExtension().setExchangeFactory(new
PooledExchangeFactory());
+ return camelContext;
+ }
+
+ @Override
+ protected int getShutdownTimeout() {
+ // the exchange that failed with a VirtualMachineError stays inflight
(CAMEL-27515)
+ return 1;
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("timer:pooled?period=50&synchronous=true")
+ .routeId(ROUTE_ID)
+ .process(exchange -> {
+ exchange.getMessage().setHeader("marker", "kept");
+ failed.set(exchange);
+ throw new StackOverflowError("simulated
StackOverflowError in a pooled timer route");
+ });
+ }
+ };
+ }
+}
diff --git
a/core/camel-core/src/test/java/org/apache/camel/component/timer/TimerVirtualMachineErrorTest.java
b/core/camel-core/src/test/java/org/apache/camel/component/timer/TimerVirtualMachineErrorTest.java
index 61e57b2bbe89..2866ac72645d 100644
---
a/core/camel-core/src/test/java/org/apache/camel/component/timer/TimerVirtualMachineErrorTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/component/timer/TimerVirtualMachineErrorTest.java
@@ -24,6 +24,8 @@ import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
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.assertTrue;
/**
@@ -42,15 +44,33 @@ public class TimerVirtualMachineErrorTest extends
ContextTestSupport {
private volatile boolean routeAHasThrown;
/** Open once route B fires at least once after route A has already thrown
its Error. */
private final CountDownLatch routeBFiredAfterError = new CountDownLatch(1);
+ /** Counts how many times route B has fired. */
+ private final AtomicInteger routeBFireCount = new AtomicInteger();
@Test
- public void sharedTimerSurvivesStackOverflowErrorInSiblingRoute() throws
InterruptedException {
+ public void sharedTimerSurvivesStackOverflowErrorInSiblingRoute() throws
Exception {
// Wait up to 5 seconds for route B to fire at least once after route
A has thrown.
// Before the fix this never happens: the StackOverflowError escapes
run() and kills
// the shared java.util.Timer thread, which silently cancels both
timer tasks.
boolean firedAfterError = routeBFiredAfterError.await(5,
TimeUnit.SECONDS);
assertTrue(firedAfterError,
"route B must keep firing after a StackOverflowError in route
A (shared timer must survive)");
+
+ // the timer task of route A is cancelled: while route B fires several
more times, route A does not fire again
+ int routeBCount = routeBFireCount.get();
+ await().atMost(5, TimeUnit.SECONDS).until(() -> routeBFireCount.get()
>= routeBCount + 5);
+ assertEquals(3, routeAFireCount.get());
+
+ // restarting route A makes it fire again
+ context.getRouteController().stopRoute("route-a");
+ context.getRouteController().startRoute("route-a");
+ await().atMost(5, TimeUnit.SECONDS).until(() -> routeAFireCount.get()
> 3);
+ }
+
+ @Override
+ protected int getShutdownTimeout() {
+ // the exchange that failed with a VirtualMachineError can stay
inflight (CAMEL-27515)
+ return 1;
}
@Override
@@ -58,13 +78,13 @@ public class TimerVirtualMachineErrorTest extends
ContextTestSupport {
return new RouteBuilder() {
@Override
public void configure() {
- // Route A: throws a StackOverflowError on its third exchange.
+ // Route A: throws a StackOverflowError on its third exchange
only, so that it fires again once restarted.
// Uses synchronous=true so the error propagates synchronously
through the timer task.
from("timer:" + TIMER_NAME + "?period=50&synchronous=true")
.routeId("route-a")
.process(exchange -> {
int count = routeAFireCount.incrementAndGet();
- if (count >= 3) {
+ if (count == 3) {
routeAHasThrown = true;
throw new StackOverflowError("simulated
StackOverflowError in route A");
}
@@ -76,6 +96,7 @@ public class TimerVirtualMachineErrorTest extends
ContextTestSupport {
from("timer:" + TIMER_NAME + "?period=50&synchronous=true")
.routeId("route-b")
.process(exchange -> {
+ routeBFireCount.incrementAndGet();
if (routeAHasThrown) {
routeBFiredAfterError.countDown();
}