gnodet-bot commented on code in PR #30623:
URL: https://github.com/apache/camel/pull/30623#discussion_r4663240619


##########
core/camel-support/src/main/java/org/apache/camel/support/cache/ServicePool.java:
##########
@@ -279,44 +395,93 @@ public int size() {
 
         @Override
         public void stop() {
-            S toStop;
+            stopped.set(true);
+            S toStop = takeService();
+            pool.remove(endpoint, this);
+            if (toStop != null) {
+                singlePoolEvicted.remove(toStop, this);
+            }
+            doStop(toStop);
+            if (evicted && toStop != null) {
+                // an evicted pool whose service was still in use (stopped 
with the ServicePool): stop its endpoint as
+                // well when nothing else uses it, as its last release would 
have done
+                stopEndpointIfUnused();
+            }
+        }
+
+        /**
+         * Takes the service out of the pool, under the lock that creates the 
services, so a creation in progress either
+         * completes before (and its service is taken) or sees the pool stopped
+         */
+        private S takeService() {
             lock.lock();
             try {
-                toStop = s;
+                S answer = s;
                 s = null;
+                return answer;
             } finally {
                 lock.unlock();
             }
-            doStop(toStop);
-            pool.remove(endpoint);
         }
 
         @Override
         public void evict(S s) {
-            singlePoolEvicted.putIfAbsent(endpoint, this);
+            if (s != this.s || evicted) {
+                // a service of an evicted pool of this endpoint, which an 
acquire in progress put in the cache again: its
+                // pool stops it when it is no longer in use
+                return;
+            }
+            // keep track of the evicted pool before it leaves the pool map, 
so the users of s can release it
+            singlePoolEvicted.put(s, this);
+            pool.remove(endpoint, this);
+            evicted = true;
+            // stopped after the cache operation (if idle), not here under the 
write lock of the cache
+            evictedToStop.add(this);
         }
 
-        @Override
-        public void cleanUp() {
-            cleanupEvicts();
+        /**
+         * Stops the evicted service if it has no more users
+         */
+        private void stopEvicted() {
+            // the releases are summed first: an acquire is counted before its 
release, so every release seen here has
+            // its acquire seen in the sum below, and an acquire of a user 
that may still use s (it was counted before s
+            // was evicted) is seen as well, so the counts are only equal when 
s has no more users
+            long released = releases.sum();
+            if (acquires.sum() != released || !stopped.compareAndSet(false, 
true)) {

Review Comment:
   🔍 **Low — JMM visibility guarantee: add brief inline note**
   
   The `releases.sum()` → `acquires.sum()` ordering relies on `volatile boolean 
evicted` providing the cross-thread visibility: the volatile write of `evicted 
= true` in `evict()` and the volatile read of `evicted` in `retain()` create a 
happens-before edge that makes the `LongAdder` cell writes visible across 
threads.
   
   The existing comment explains the invariant well for the read ordering (why 
releases are summed first), but a brief note that the volatile `evicted` flag 
provides the cross-thread visibility guarantee would help future maintainers 
reason about JMM correctness — especially since `LongAdder` cells are updated 
via relaxed CAS internally and do not themselves establish happens-before with 
reads in other threads.
   
   Consider extending the comment:
   ```suggestion
               // the releases are summed first: an acquire is counted before 
its release, so every release seen here has
               // its acquire seen in the sum below, and an acquire of a user 
that may still use s (it was counted before s
               // was evicted) is seen as well, so the counts are only equal 
when s has no more users.
               // The volatile write of `evicted = true` in evict() establishes 
happens-before with the volatile read in
               // retain(), ensuring the LongAdder cell writes from all prior 
acquires and releases are visible here.
   ```



##########
core/camel-core/src/test/java/org/apache/camel/support/cache/SinglePoolEvictionLockTest.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.support.cache;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+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.TimeoutException;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.AsyncProducer;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Consumer;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Endpoint;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.Producer;
+import org.apache.camel.support.DefaultAsyncProducer;
+import org.apache.camel.support.DefaultEndpoint;
+import org.apache.camel.support.service.ServiceHelper;
+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.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * The LRU cache of a ServicePool calls onEvict while it holds its write lock. 
The stop of an evicted idle singleton
+ * producer (and the in-use check and stop of its endpoint, which take the 
lock of the ServicePool) must therefore run
+ * after the cache operation, not inside the eviction: otherwise a stop of the 
ServicePool (which holds its lock and
+ * clears the cache) deadlocks with an acquire that evicts, and a slow stop of 
the evicted producer blocks every acquire
+ * of the cache.
+ */
+class SinglePoolEvictionLockTest extends ContextTestSupport {
+
+    // daemon threads: on failure they stay blocked, and must not keep the JVM 
alive
+    private final ExecutorService executor = Executors.newCachedThreadPool(r 
-> {
+        Thread t = new Thread(r, "SinglePoolEvictionLockTest");
+        t.setDaemon(true);
+        return t;
+    });
+
+    @AfterEach
+    void shutdownExecutor() {
+        executor.shutdownNow();
+    }
+
+    @Test
+    void testStopOfThePoolDoesNotDeadlockWithAnAcquireThatEvicts() throws 
Exception {
+        PausingServicePool pool = new PausingServicePool(1);
+        TestEndpoint a = new TestEndpoint("test:a", context, true);
+        TestEndpoint b = new TestEndpoint("test:b", context, true);
+        // the stop of the pool stops the pool of b before the pool of a (the 
order of the pool map)
+        Map<Endpoint, Boolean> order = new ConcurrentHashMap<>();
+        order.put(a, true);
+        order.put(b, true);
+        assertSame(b, order.keySet().iterator().next());

Review Comment:
   🔍 **Low — CHM ordering guard: document the URI choice**
   
   The `assertSame(b, order.keySet().iterator().next())` precondition guards 
that `b`'s pool is stopped before `a`'s, which is the scenario the test needs. 
This relies on `DefaultEndpoint.hashCode()` placing `"test:b"` in a lower CHM 
bucket than `"test:a"` with the current URIs.
   
   This is deterministic for these URIs, but the reason is non-obvious. 
Consider a brief comment explaining the choice, so a future refactor of the URI 
strings doesn't silently break the test's precondition:
   
   ```suggestion
           // "test:b" hashes to a lower ConcurrentHashMap bucket than "test:a" 
with DefaultEndpoint.hashCode()
           // (URI hashCode * 37 + 1), so the pool map iterates b before a and 
the stop of the pool stops b first.
           // The test needs this order to trigger the specific deadlock 
scenario.
           Map<Endpoint, Boolean> order = new ConcurrentHashMap<>();
           order.put(a, true);
           order.put(b, true);
           assertSame(b, order.keySet().iterator().next());
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to