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 404256bd1dd3 CAMEL-27489: camel-core - context reloads run one at a 
time, so two reloads at the same time no longer leave a copy of every route 
(#30806)
404256bd1dd3 is described below

commit 404256bd1dd35d9132ef43660af944e6a687af95
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 14:33:37 2026 +0530

    CAMEL-27489: camel-core - context reloads run one at a time, so two reloads 
at the same time no longer leave a copy of every route (#30806)
    
    DefaultContextReloadStrategy.onReload had no mutual exclusion. A reload
    removes all the routes and creates them again from their definitions,
    and lockModel only marks the calling thread, so two reloads that
    overlapped (a secret refresh task and JMX, the developer console, the
    CLI, or the Kubernetes and IBM refresh tasks on their own threads) both
    removed the routes and both created them again: the context ended with
    two Route objects for each route id, which a later reload did not remove.
    
    onReload now runs under a ReentrantLock: a reload requested while
    another one runs waits for it to complete and then runs its own reload,
    so every request is still served and sees the state at the time it runs.
    The lock is reentrant, so a reload that triggers a reload on the same
    thread does not block.
    
    New CamelContextReloadStrategyConcurrentTest: the first reload is held
    right after it removed the routes, a second reload is requested, then
    the first one goes on; the context must end with one copy of each route,
    all started, and both reloads succeeded.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../CamelContextReloadStrategyConcurrentTest.java  | 127 +++++++++++++++++++++
 .../support/DefaultContextReloadStrategy.java      |  18 +++
 2 files changed, 145 insertions(+)

diff --git 
a/core/camel-core/src/test/java/org/apache/camel/impl/CamelContextReloadStrategyConcurrentTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/impl/CamelContextReloadStrategyConcurrentTest.java
new file mode 100644
index 000000000000..e1e22a40c15c
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/impl/CamelContextReloadStrategyConcurrentTest.java
@@ -0,0 +1,127 @@
+/*
+ * 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.impl;
+
+import java.util.List;
+import java.util.Map;
+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 org.apache.camel.Consumer;
+import org.apache.camel.Endpoint;
+import org.apache.camel.Processor;
+import org.apache.camel.Producer;
+import org.apache.camel.Route;
+import org.apache.camel.ServiceStatus;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.support.DefaultComponent;
+import org.apache.camel.support.DefaultConsumer;
+import org.apache.camel.support.DefaultContextReloadStrategy;
+import org.apache.camel.support.DefaultEndpoint;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Two reloads requested at the same time (for example a secret refresh task 
and JMX) run one after the other, and the
+ * context ends with one copy of each route.
+ */
+class CamelContextReloadStrategyConcurrentTest {
+
+    // the next creation of the pause endpoint waits, so that a reload is held 
after it removed the routes
+    private final AtomicBoolean pauseNext = new AtomicBoolean();
+    private final CountDownLatch firstPaused = new CountDownLatch(1);
+    // counted down when another reload creates the pause endpoint, that is 
after it removed the routes too
+    private final CountDownLatch otherCreating = new CountDownLatch(1);
+
+    private final ExecutorService pool = Executors.newFixedThreadPool(2);
+    private DefaultCamelContext context;
+
+    @AfterEach
+    void tearDown() {
+        pool.shutdownNow();
+        if (context != null) {
+            context.stop();
+        }
+    }
+
+    @Test
+    void concurrentReloadsKeepOneCopyOfEachRoute() throws Exception {
+        context = new DefaultCamelContext();
+        context.addComponent("pause", new PauseComponent());
+        DefaultContextReloadStrategy reload = new 
DefaultContextReloadStrategy();
+        context.addService(reload);
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("pause:a").routeId("a").log("${body}");
+                from("direct:b").routeId("b").log("${body}");
+                from("direct:c").routeId("c").log("${body}");
+            }
+        });
+        context.start();
+        assertEquals(3, context.getRoutes().size());
+
+        pauseNext.set(true);
+        Future<?> first = pool.submit(() -> reload.onReload("first"));
+        assertTrue(firstPaused.await(20, TimeUnit.SECONDS), "the first reload 
creates the routes again");
+        // the first reload removed the routes and waits while it creates them 
again
+        Future<?> second = pool.submit(() -> reload.onReload("second"));
+        first.get(20, TimeUnit.SECONDS);
+        second.get(20, TimeUnit.SECONDS);
+
+        List<String> ids = 
context.getRoutes().stream().map(Route::getRouteId).sorted().toList();
+        assertEquals(List.of("a", "b", "c"), ids, "one copy of each route");
+        // a second consumer of direct:b would fail the start of a copy of 
route b
+        assertEquals(0, reload.getFailedCounter(), "no reload fails");
+        assertEquals(2, reload.getReloadCounter(), "both reloads run");
+        for (String id : ids) {
+            assertEquals(ServiceStatus.Started, 
context.getRouteController().getRouteStatus(id));
+        }
+    }
+
+    private final class PauseComponent extends DefaultComponent {
+        @Override
+        protected Endpoint createEndpoint(String uri, String remaining, 
Map<String, Object> parameters)
+                throws Exception {
+            if (pauseNext.compareAndSet(true, false)) {
+                firstPaused.countDown();
+                // with reloads one at a time, the other reload waits for this 
one, and this wait times out
+                otherCreating.await(2, TimeUnit.SECONDS);
+            } else if (firstPaused.getCount() == 0) {
+                otherCreating.countDown();
+            }
+            return new DefaultEndpoint(uri, this) {
+                @Override
+                public Producer createProducer() {
+                    throw new UnsupportedOperationException();
+                }
+
+                @Override
+                public Consumer createConsumer(Processor processor) {
+                    return new DefaultConsumer(this, processor);
+                }
+            };
+        }
+    }
+}
diff --git 
a/core/camel-support/src/main/java/org/apache/camel/support/DefaultContextReloadStrategy.java
 
b/core/camel-support/src/main/java/org/apache/camel/support/DefaultContextReloadStrategy.java
index feaaf17072f0..d0f978c1a3c0 100644
--- 
a/core/camel-support/src/main/java/org/apache/camel/support/DefaultContextReloadStrategy.java
+++ 
b/core/camel-support/src/main/java/org/apache/camel/support/DefaultContextReloadStrategy.java
@@ -19,6 +19,8 @@ package org.apache.camel.support;
 import java.util.LinkedHashSet;
 import java.util.Properties;
 import java.util.Set;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
 
 import org.apache.camel.CamelContext;
 import org.apache.camel.Component;
@@ -43,6 +45,9 @@ public class DefaultContextReloadStrategy extends 
ServiceSupport implements Cont
 
     private static final Logger LOG = 
LoggerFactory.getLogger(DefaultContextReloadStrategy.class);
 
+    // one reload at a time: a reload removes all the routes and then creates 
them again from their definitions, so two
+    // reloads that overlap would each create a copy of every route
+    private final Lock reloadLock = new ReentrantLock();
     private CamelContext camelContext;
     private int succeeded;
     private int failed;
@@ -63,8 +68,21 @@ public class DefaultContextReloadStrategy extends 
ServiceSupport implements Cont
         onReload("JMX Management");
     }
 
+    /**
+     * Reloads the CamelContext. Reloads run one at a time: a reload requested 
while another one runs (from JMX, the
+     * developer console or a secret refresh task, for example) waits for it 
to complete, and then runs.
+     */
     @Override
     public void onReload(Object source) {
+        reloadLock.lock();
+        try {
+            doReload(source);
+        } finally {
+            reloadLock.unlock();
+        }
+    }
+
+    private void doReload(Object source) {
         LOG.info("Reloading CamelContext ({}) triggered by: {}", 
camelContext.getName(), source);
         try {
             lastError = null;

Reply via email to