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 3d23565f1c30 CAMEL-27336: camel-core - Do not stop an evicted
singleton producer while it is in use (#30623)
3d23565f1c30 is described below
commit 3d23565f1c30461926d033c25a517c5a7744f68e
Author: allthingssecurity <[email protected]>
AuthorDate: Mon Nov 23 19:38:19 2026 +0530
CAMEL-27336: camel-core - Do not stop an evicted singleton producer while
it is in use (#30623)
ServicePool.SinglePool, the pool of a singleton producer (or polling
consumer) in every DefaultProducerCache and DefaultConsumerCache, kept no
record of who used its producer, so an eviction from the LRU cache could stop a
producer during a send, a stale singlePoolEvicted entry could stop the next
pool of the endpoint, and SinglePool.acquire could return null. The
lastUsedProducer fast path of DefaultProducerCache could hand out a stopped
producer.
SinglePool now counts the acquires and the releases of its producer in two
LongAdders, with a full fence after each count. An eviction takes the pool out
of the pool map at once (remove(endpoint, this)), so the next acquire creates a
new pool. The evicted producer is stopped, with its endpoint when nothing else
uses it, when nobody uses it, or by its last release. The eviction only marks
and queues the pool; the producer is stopped after the LRU cache lock is
released (from acquire an [...]
Behaviour change: an evicted singleton producer that is acquired and never
released is stopped when the producer cache stops, not by the eviction.
Tests: ProducerCacheSingletonEvictionTest, SinglePoolAcquireEvictionTest
and SinglePoolEvictionLockTest (camel-core).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../impl/ProducerCacheSingletonEvictionTest.java | 372 +++++++++++++++++++++
.../cache/SinglePoolAcquireEvictionTest.java | 101 ++++++
.../support/cache/SinglePoolEvictionLockTest.java | 239 +++++++++++++
.../camel/support/cache/DefaultProducerCache.java | 4 +-
.../apache/camel/support/cache/ServicePool.java | 292 ++++++++++++----
5 files changed, 951 insertions(+), 57 deletions(-)
diff --git
a/core/camel-core/src/test/java/org/apache/camel/impl/ProducerCacheSingletonEvictionTest.java
b/core/camel-core/src/test/java/org/apache/camel/impl/ProducerCacheSingletonEvictionTest.java
new file mode 100644
index 000000000000..17d0a0b37ace
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/impl/ProducerCacheSingletonEvictionTest.java
@@ -0,0 +1,372 @@
+/*
+ * 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.lang.reflect.Method;
+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.function.Function;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.AsyncProducer;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Component;
+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.Service;
+import org.apache.camel.support.DefaultAsyncProducer;
+import org.apache.camel.support.DefaultComponent;
+import org.apache.camel.support.DefaultEndpoint;
+import org.apache.camel.support.cache.DefaultProducerCache;
+import org.apache.camel.support.cache.ProducerServicePool;
+import org.apache.camel.support.service.ServiceHelper;
+import org.apache.camel.util.function.ThrowingFunction;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Singleton producers are shared by all the users of a producer cache. When
one of them is evicted from the cache, it
+ * must not be stopped (nor its endpoint) while it is in use, it must not be
handed out again, and the eviction must
+ * only affect the pool of that producer.
+ */
+class ProducerCacheSingletonEvictionTest extends ContextTestSupport {
+
+ private final ExecutorService executor =
Executors.newSingleThreadExecutor();
+
+ @Override
+ protected void doPostSetup() {
+ context.addComponent("my", new MyComponent());
+ }
+
+ @AfterEach
+ void shutdownExecutor() {
+ executor.shutdownNow();
+ }
+
+ @Test
+ void testEvictedProducerNotStoppedWhileProcessing() throws Exception {
+ DefaultProducerCache cache = new DefaultProducerCache(this, context,
1);
+ cache.start();
+ MyEndpoint a = (MyEndpoint) context.getEndpoint("my:a");
+ MyEndpoint b = (MyEndpoint) context.getEndpoint("my:b");
+ a.inProcess = new CountDownLatch(1);
+ a.proceed = new CountDownLatch(1);
+
+ // worker 1 sends to a, and the producer of a waits inside process()
+ Future<Exchange> sent = executor.submit(() -> cache.send(a,
a.createExchange(), null));
+ assertTrue(a.inProcess.await(10, TimeUnit.SECONDS));
+ MyProducer pa = a.lastProducer;
+
+ // worker 2 sends to b: the cache (capacity 1) evicts the producer of a
+ cache.send(b, b.createExchange(), null);
+ assertTrue(pa.isStarted(), "The evicted producer should not be stopped
while it is processing");
+ assertTrue(a.isStarted(), "The endpoint of the evicted producer should
not be stopped while it is used");
+
+ a.proceed.countDown();
+ Exchange done = sent.get(10, TimeUnit.SECONDS);
+ assertNull(done.getException(), "The send should not fail");
+
+ // the producer is stopped when it is released, and the dynamic
endpoint as nothing else uses it
+ assertTrue(pa.isStopped(), "The evicted producer should be stopped
when it is released");
+ assertTrue(a.isStopped(), "The dynamic endpoint not in use should be
stopped to free resources");
+ cache.stop();
+ }
+
+ @Test
+ void testEvictedProducerInUseIsStoppedWhenReleased() throws Exception {
+ MyServicePool pool = new MyServicePool(1);
+ Endpoint a = context.getEndpoint("my:a");
+ Endpoint b = context.getEndpoint("my:b");
+
+ AsyncProducer pa1 = pool.acquire(a);
+ // acquiring b evicts pa1, which is in use
+ AsyncProducer pb = pool.acquire(b);
+ assertTrue(isStarted(pa1), "The evicted producer should not be stopped
while it is in use");
+
+ // the evicted producer is not handed out again
+ AsyncProducer pa2 = pool.acquire(a);
+ assertNotSame(pa1, pa2);
+ assertTrue(isStarted(pa2), "The acquired producer should be started");
+
+ // the cache evicts pa1 again (an acquire in progress put it in the
cache again): this must not affect pa2
+ pool.evict(pa1);
+ assertSame(pa2, pool.acquire(a));
+ pool.release(a, pa2);
+ assertTrue(isStarted(pa1), "The evicted producer should not be stopped
while it is in use");
+ assertTrue(isStarted(pa2), "The current producer should not be stopped
by the eviction of another one");
+
+ pool.release(a, pa1);
+ assertTrue(isStopped(pa1), "The evicted producer should be stopped
when it is released");
+ assertTrue(isStarted(pa2), "The current producer should not be stopped
by the release of another one");
+ assertTrue(ServiceHelper.isStarted(a), "The endpoint should not be
stopped while the current producer uses it");
+
+ pool.release(a, pa2);
+ pool.release(b, pb);
+ pool.stop();
+ }
+
+ @Test
+ void testEvictionDoesNotAffectTheNewPoolOfTheEndpoint() throws Exception {
+ MyServicePool pool = new MyServicePool(1);
+ Endpoint a = context.getEndpoint("my:a");
+
+ AsyncProducer pa1 = pool.acquire(a);
+ pool.release(a, pa1);
+ // acquiring b evicts pa1, which is idle
+ AsyncProducer pb = pool.acquire(b());
+ assertTrue(isStopped(pa1), "The evicted idle producer should be
stopped");
+
+ // resolve the endpoint again (as toD does) and acquire it twice: one
pool and one producer of a started endpoint
+ Endpoint a2 = context.getEndpoint("my:a");
+ AsyncProducer pa2 = pool.acquire(a2);
+ assertTrue(isStarted(pa2), "The acquired producer should be started");
+ assertTrue(ServiceHelper.isStarted(a2), "The endpoint of the acquired
producer should be started");
+ AsyncProducer pa3 = pool.acquire(a2);
+ assertSame(pa2, pa3, "A singleton endpoint should have one producer");
+ pool.release(a2, pa3);
+ pool.release(a2, pa2);
+ assertTrue(isStarted(pa2), "The current producer should be started");
+ assertTrue(ServiceHelper.isStarted(a2), "The endpoint of the current
producer should be started");
+
+ pool.release(b(), pb);
+ pool.stop();
+ }
+
+ @Test
+ void testFastPathDoesNotHandOutEvictedProducer() {
+ MyProducerCache cache = new MyProducerCache(context);
+ cache.start();
+ Endpoint a = context.getEndpoint("my:a");
+
+ // pa1 is in use, and is the last used producer of the cache
+ AsyncProducer pa1 = cache.acquireProducer(a);
+ cache.evict(pa1);
+ assertTrue(isStarted(pa1), "The evicted producer should not be stopped
while it is in use");
+
+ AsyncProducer pa2 = cache.acquireProducer(a);
+ assertNotSame(pa1, pa2, "The evicted producer should not be handed out
again");
+ assertTrue(isStarted(pa2), "The acquired producer should be started");
+
+ cache.releaseProducer(a, pa1);
+ assertTrue(isStopped(pa1), "The evicted producer should be stopped
when it is released");
+ cache.releaseProducer(a, pa2);
+ assertTrue(isStarted(pa2), "The current producer should not be
stopped");
+
+ // the fast path acquires the current producer, and counts it as in use
+ AsyncProducer pa3 = cache.acquireProducer(a);
+ assertSame(pa2, pa3);
+ cache.evict(pa3);
+ assertTrue(isStarted(pa3), "The evicted producer should not be stopped
while it is in use");
+ cache.releaseProducer(a, pa3);
+ assertTrue(isStopped(pa3), "The evicted producer should be stopped
when it is released");
+ cache.stop();
+ }
+
+ @Test
+ void testCreatorReturningNullFails() throws Exception {
+ Endpoint a = context.getEndpoint("my:a");
+ MyServicePool pool = new MyServicePool(1, e -> null,
Producer::getEndpoint);
+ try {
+ // fails as main did, instead of retrying the same pool for ever
+ Future<Exception> failed = executor.submit(() ->
assertThrows(IllegalStateException.class, () -> pool.acquire(a)));
+ assertTrue(failed.get(10,
TimeUnit.SECONDS).getMessage().startsWith("No service created from endpoint"));
+ // and again, as the pool is not left in a bad state
+ assertThrows(IllegalStateException.class, () -> pool.acquire(a));
+ } finally {
+ // ends a retry loop that would not end by itself
+ pool.stop();
+ }
+ }
+
+ @Test
+ void testStopOfThePoolStopsTheEndpointOfAnEvictedProducerInUse() throws
Exception {
+ MyServicePool pool = new MyServicePool(1);
+ Endpoint a = context.getEndpoint("my:a");
+
+ AsyncProducer pa = pool.acquire(a);
+ // acquiring b evicts pa, which is in use
+ AsyncProducer pb = pool.acquire(b());
+ pool.release(b(), pb);
+ assertTrue(isStarted(pa), "The evicted producer should not be stopped
while it is in use");
+
+ // the producer cache stops (or is purged) before pa is released: pa
is stopped, and its dynamic endpoint as
+ // nothing else uses it, as its release would have done
+ pool.stop();
+ assertTrue(isStopped(pa), "The evicted producer should be stopped when
the pool stops");
+ assertTrue(ServiceHelper.isStopped(a), "The dynamic endpoint not in
use should be stopped to free resources");
+ }
+
+ @Test
+ void testReacquireOfNullIsNotCountedAsAUser() throws Exception {
+ MyEndpoint a = (MyEndpoint) context.getEndpoint("my:a");
+ MyServicePool pool = new MyServicePool(1, p -> p != null ?
p.getEndpoint() : a);
+ // the pool of a has no producer yet: creating it failed
+ a.failCreate = true;
+ assertThrows(IllegalStateException.class, () -> pool.acquire(a));
+ a.failCreate = false;
+
+ assertFalse(reacquire(pool, null), "A null producer should not be
acquired");
+
+ // no user is left behind: the producer is stopped when it is evicted
while idle
+ AsyncProducer pa = pool.acquire(a);
+ pool.release(a, pa);
+ pool.evict(pa);
+ assertTrue(isStopped(pa), "The evicted idle producer should be
stopped");
+ pool.stop();
+ }
+
+ private Endpoint b() {
+ return context.getEndpoint("my:b");
+ }
+
+ private static boolean reacquire(ProducerServicePool pool, AsyncProducer
producer) throws Exception {
+ // package-private in ServicePool, where DefaultProducerCache calls it
+ Method method =
ProducerServicePool.class.getSuperclass().getDeclaredMethod("reacquire",
Service.class);
+ method.setAccessible(true);
+ return (boolean) method.invoke(pool, producer);
+ }
+
+ private static boolean isStarted(AsyncProducer producer) {
+ return ((MyProducer) producer).isStarted();
+ }
+
+ private static boolean isStopped(AsyncProducer producer) {
+ return ((MyProducer) producer).isStopped();
+ }
+
+ private static final class MyServicePool extends ProducerServicePool {
+
+ MyServicePool(int capacity) {
+ this(capacity, Producer::getEndpoint);
+ }
+
+ MyServicePool(int capacity, Function<AsyncProducer, Endpoint>
getEndpoint) {
+ this(capacity, Endpoint::createAsyncProducer, getEndpoint);
+ }
+
+ MyServicePool(int capacity, ThrowingFunction<Endpoint, AsyncProducer,
Exception> creator,
+ Function<AsyncProducer, Endpoint> getEndpoint) {
+ super(creator, getEndpoint, capacity);
+ start();
+ }
+
+ void evict(AsyncProducer producer) {
+ // as the LRU cache: onEvict, then the evicted idle producer is
stopped after the cache operation
+ onEvict(producer);
+ cleanUp();
+ }
+ }
+
+ private static final class MyProducerCache extends DefaultProducerCache {
+
+ private MyServicePool pool;
+
+ MyProducerCache(CamelContext context) {
+ super(ProducerCacheSingletonEvictionTest.class, context, 1);
+ }
+
+ @Override
+ protected ProducerServicePool createServicePool(CamelContext
camelContext, int cacheSize) {
+ pool = new MyServicePool(cacheSize);
+ return pool;
+ }
+
+ void evict(AsyncProducer producer) {
+ pool.evict(producer);
+ }
+ }
+
+ private static final class MyComponent extends DefaultComponent {
+
+ @Override
+ protected Endpoint createEndpoint(String uri, String remaining,
Map<String, Object> parameters) {
+ return new MyEndpoint(uri, this);
+ }
+ }
+
+ private static final class MyEndpoint extends DefaultEndpoint {
+ volatile CountDownLatch inProcess;
+ volatile CountDownLatch proceed;
+ volatile MyProducer lastProducer;
+ volatile boolean failCreate;
+
+ MyEndpoint(String uri, Component component) {
+ super(uri, component);
+ }
+
+ @Override
+ public Producer createProducer() {
+ if (failCreate) {
+ throw new IllegalStateException("Cannot create the producer");
+ }
+ MyProducer producer = new MyProducer(this);
+ lastProducer = producer;
+ return producer;
+ }
+
+ @Override
+ public Consumer createConsumer(Processor processor) {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ private static final class MyProducer extends DefaultAsyncProducer {
+
+ MyProducer(MyEndpoint endpoint) {
+ super(endpoint);
+ }
+
+ @Override
+ public boolean process(Exchange exchange, AsyncCallback callback) {
+ MyEndpoint endpoint = (MyEndpoint) getEndpoint();
+ CountDownLatch in = endpoint.inProcess;
+ if (in != null) {
+ endpoint.inProcess = null;
+ in.countDown();
+ try {
+ if (!endpoint.proceed.await(10, TimeUnit.SECONDS)) {
+ exchange.setException(new IllegalStateException("Not
allowed to proceed"));
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ exchange.setException(e);
+ }
+ if (!isStarted()) {
+ // like a producer whose resources are released when it is
stopped
+ exchange.setException(new IllegalStateException("Producer
stopped while processing"));
+ }
+ }
+ callback.done(true);
+ return true;
+ }
+ }
+}
diff --git
a/core/camel-core/src/test/java/org/apache/camel/support/cache/SinglePoolAcquireEvictionTest.java
b/core/camel-core/src/test/java/org/apache/camel/support/cache/SinglePoolAcquireEvictionTest.java
new file mode 100644
index 000000000000..10e1ebd0c4f8
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/support/cache/SinglePoolAcquireEvictionTest.java
@@ -0,0 +1,101 @@
+/*
+ * 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.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.AsyncProducer;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Endpoint;
+import org.apache.camel.Producer;
+import org.apache.camel.support.service.ServiceHelper;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * An acquire of a singleton producer that is evicted while the acquire is in
progress must still return the producer it
+ * acquired, and the producer must not be stopped until it is released. The
test pauses the acquire in the
+ * package-private hook {@code ServicePool.onSingleAcquired}, after the pool
read and counted its producer.
+ */
+class SinglePoolAcquireEvictionTest extends ContextTestSupport {
+
+ private final ExecutorService executor =
Executors.newSingleThreadExecutor();
+
+ @AfterEach
+ void shutdownExecutor() {
+ executor.shutdownNow();
+ }
+
+ @Test
+ void testAcquireDoesNotReturnNullWhenEvictedMeanwhile() throws Exception {
+ PausingServicePool pool = new PausingServicePool(1);
+ Endpoint a = context.getEndpoint("seda:a");
+ Endpoint b = context.getEndpoint("seda:b");
+ AsyncProducer pa = pool.acquire(a);
+ pool.release(a, pa);
+
+ // the next acquire of pa pauses after the pool read it
+ pool.pauseOn = pa;
+ Future<AsyncProducer> acquired = executor.submit(() ->
pool.acquire(a));
+ assertTrue(pool.paused.await(10, TimeUnit.SECONDS));
+
+ // acquiring b evicts pa while the other thread is acquiring it
+ AsyncProducer pb = pool.acquire(b);
+ pool.proceed.countDown();
+ AsyncProducer got = acquired.get(10, TimeUnit.SECONDS);
+ assertNotNull(got, "Acquire should not return null while the pool is
started");
+ assertSame(pa, got);
+ assertTrue(ServiceHelper.isStarted(pa), "The evicted producer should
not be stopped while it is in use");
+
+ pool.release(a, got);
+ assertTrue(ServiceHelper.isStopped(pa), "The evicted producer should
be stopped when it is released");
+ pool.release(b, pb);
+ pool.stop();
+ }
+
+ private static final class PausingServicePool extends ProducerServicePool {
+ final CountDownLatch paused = new CountDownLatch(1);
+ final CountDownLatch proceed = new CountDownLatch(1);
+ volatile AsyncProducer pauseOn;
+
+ PausingServicePool(int capacity) {
+ super(Endpoint::createAsyncProducer, Producer::getEndpoint,
capacity);
+ start();
+ }
+
+ @Override
+ void onSingleAcquired(AsyncProducer s) {
+ if (s != null && s == pauseOn) {
+ pauseOn = null;
+ paused.countDown();
+ try {
+ proceed.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+ }
+}
diff --git
a/core/camel-core/src/test/java/org/apache/camel/support/cache/SinglePoolEvictionLockTest.java
b/core/camel-core/src/test/java/org/apache/camel/support/cache/SinglePoolEvictionLockTest.java
new file mode 100644
index 000000000000..d3a943ec5a01
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/support/cache/SinglePoolEvictionLockTest.java
@@ -0,0 +1,239 @@
+/*
+ * 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): with
+ // DefaultEndpoint.hashCode() (the hash code of the URI * 37 + 1),
test:b is in a lower bucket of a
+ // ConcurrentHashMap than test:a, so b comes first. The assertSame
below fails if other URIs change this order
+ Map<Endpoint, Boolean> order = new ConcurrentHashMap<>();
+ order.put(a, true);
+ order.put(b, true);
+ assertSame(b, order.keySet().iterator().next());
+
+ AsyncProducer pa = pool.acquire(a);
+ pool.release(a, pa);
+
+ // an acquire of b creates its producer, and pauses before it puts it
in the cache
+ pool.pauseOn = b;
+ Future<AsyncProducer> acquired = executor.submit(() ->
pool.acquire(b));
+ assertTrue(pool.paused.await(10, TimeUnit.SECONDS));
+ Thread acquirer = pool.pausedThread;
+ BlockingStopProducer pb = (BlockingStopProducer) pool.pausedService;
+ pb.blockStop();
+
+ // the pool stops, and waits in the stop of pb while it holds its lock
+ Future<?> stopped = executor.submit(pool::stop);
+ assertTrue(pb.stopEntered.await(10, TimeUnit.SECONDS));
+
+ // the acquire puts pb in the cache, which evicts pa (idle): the stop
of the evicted pa needs the lock of the
+ // pool
+ pool.proceed.countDown();
+ await().atMost(10, TimeUnit.SECONDS).until(() -> isWaitingIn(acquirer,
"stopEvicted"));
+
+ // the stop of the pool goes on, and clears the cache
+ pb.releaseStop();
+ try {
+ stopped.get(10, TimeUnit.SECONDS);
+ assertNotNull(acquired.get(10, TimeUnit.SECONDS));
+ } catch (TimeoutException e) {
+ fail("The stop of the pool and the acquire that evicts are
deadlocked");
+ }
+ assertTrue(ServiceHelper.isStopped(pa), "The evicted producer should
be stopped");
+ }
+
+ @Test
+ void testSlowStopOfAnEvictedProducerDoesNotBlockOtherAcquires() throws
Exception {
+ PausingServicePool pool = new PausingServicePool(1);
+ TestEndpoint a = new TestEndpoint("test:a", context, true);
+ TestEndpoint b = new TestEndpoint("test:b", context, true);
+
+ BlockingStopProducer pa = (BlockingStopProducer) pool.acquire(a);
+ pool.release(a, pa);
+ pa.blockStop();
+
+ // the acquire of b evicts pa (idle), and the stop of pa waits
+ Future<AsyncProducer> acquiredB = executor.submit(() ->
pool.acquire(b));
+ assertTrue(pa.stopEntered.await(10, TimeUnit.SECONDS));
+
+ // another acquire of the cache meanwhile (a new pool and producer for
a) is not held up by the stop of pa
+ Future<AsyncProducer> acquiredA = executor.submit(() ->
pool.acquire(a));
+ try {
+ AsyncProducer pa2 = acquiredA.get(10, TimeUnit.SECONDS);
+ assertNotNull(pa2);
+ assertTrue(pa2 != pa, "The evicted producer should not be acquired
again");
+ } catch (TimeoutException e) {
+ fail("An acquire waits for the stop of an evicted producer of
another acquire");
+ } finally {
+ pa.releaseStop();
+ }
+ assertNotNull(acquiredB.get(10, TimeUnit.SECONDS));
+ pool.stop();
+ }
+
+ private static boolean isWaitingIn(Thread thread, String method) {
+ if (thread.getState() != Thread.State.WAITING && thread.getState() !=
Thread.State.TIMED_WAITING) {
+ return false;
+ }
+ for (StackTraceElement element : thread.getStackTrace()) {
+ if (method.equals(element.getMethodName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static final class PausingServicePool extends ProducerServicePool {
+ final CountDownLatch paused = new CountDownLatch(1);
+ final CountDownLatch proceed = new CountDownLatch(1);
+ volatile Endpoint pauseOn;
+ volatile Thread pausedThread;
+ volatile AsyncProducer pausedService;
+
+ PausingServicePool(int capacity) {
+ super(Endpoint::createAsyncProducer, Producer::getEndpoint,
capacity);
+ start();
+ }
+
+ @Override
+ void onSingleAcquired(AsyncProducer s) {
+ if (s != null && pauseOn != null && s.getEndpoint() == pauseOn) {
+ pauseOn = null;
+ pausedThread = Thread.currentThread();
+ pausedService = s;
+ paused.countDown();
+ try {
+ proceed.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+ }
+
+ private static final class TestEndpoint extends DefaultEndpoint {
+ private final boolean singleton;
+
+ TestEndpoint(String uri, CamelContext context, boolean singleton) {
+ super(uri, null);
+ setCamelContext(context);
+ this.singleton = singleton;
+ }
+
+ @Override
+ public boolean isSingletonProducer() {
+ return singleton;
+ }
+
+ @Override
+ public Producer createProducer() {
+ return new BlockingStopProducer(this);
+ }
+
+ @Override
+ public Consumer createConsumer(Processor processor) {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ private static final class BlockingStopProducer extends
DefaultAsyncProducer {
+ final CountDownLatch stopEntered = new CountDownLatch(1);
+ private final CountDownLatch stopReleased = new CountDownLatch(1);
+ private volatile boolean block;
+
+ BlockingStopProducer(Endpoint endpoint) {
+ super(endpoint);
+ }
+
+ void blockStop() {
+ block = true;
+ }
+
+ void releaseStop() {
+ stopReleased.countDown();
+ }
+
+ @Override
+ public boolean process(Exchange exchange, AsyncCallback callback) {
+ callback.done(true);
+ return true;
+ }
+
+ @Override
+ protected void doStop() throws Exception {
+ if (block) {
+ stopEntered.countDown();
+ stopReleased.await(20, TimeUnit.SECONDS);
+ }
+ }
+ }
+}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/cache/DefaultProducerCache.java
b/core/camel-support/src/main/java/org/apache/camel/support/cache/DefaultProducerCache.java
index b5d4719a1c2f..ed390f66126f 100644
---
a/core/camel-support/src/main/java/org/apache/camel/support/cache/DefaultProducerCache.java
+++
b/core/camel-support/src/main/java/org/apache/camel/support/cache/DefaultProducerCache.java
@@ -130,7 +130,9 @@ public class DefaultProducerCache extends ServiceSupport
implements ProducerCach
// triggering cases of false sharing
// copy reference to avoid need for synchronization and be thread safe
AsyncProducer lastUsedProducerRef = lastUsedProducer;
- if (lastUsedProducerRef != null && endpoint ==
lastUsedProducerRef.getEndpoint() && endpoint.isSingletonProducer()) {
+ if (lastUsedProducerRef != null && endpoint ==
lastUsedProducerRef.getEndpoint() && endpoint.isSingletonProducer()
+ && producers.reacquire(lastUsedProducerRef)) {
+ // the pool counts the users of a singleton producer, and an
evicted producer is no longer reacquired
return lastUsedProducerRef;
}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/cache/ServicePool.java
b/core/camel-support/src/main/java/org/apache/camel/support/cache/ServicePool.java
index c5c061c86fa8..f6fdf0c41af8 100644
---
a/core/camel-support/src/main/java/org/apache/camel/support/cache/ServicePool.java
+++
b/core/camel-support/src/main/java/org/apache/camel/support/cache/ServicePool.java
@@ -16,15 +16,20 @@
*/
package org.apache.camel.support.cache;
+import java.lang.invoke.VarHandle;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Map;
+import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.LongAdder;
import java.util.function.Function;
import org.apache.camel.CamelContext;
@@ -53,16 +58,31 @@ abstract class ServicePool<S extends Service> extends
ServiceSupport implements
private final ThrowingFunction<Endpoint, S, Exception> creator;
private final Function<S, Endpoint> getEndpoint;
private final ConcurrentMap<Endpoint, Pool<S>> pool = new
ConcurrentHashMap<>();
- // keep track of all singleton endpoints with a pooled producer that are
evicted
- // for multi pool then they have their own house-keeping for evictions
(more complex)
- private final ConcurrentMap<Endpoint, Pool<S>> singlePoolEvicted = new
ConcurrentHashMap<>();
+ // the evicted single pools whose service is still in use, by service:
they are no longer in the pool map, and the
+ // last release of the service stops it (for multi pool then they have
their own house-keeping for evictions)
+ private final ConcurrentMap<S, Pool<S>> singlePoolEvicted = new
ConcurrentHashMap<>();
+ // the single pools evicted by the LRU cache, whose service is stopped (if
idle) after the cache operation: the
+ // cache calls onEvict under its write lock, which must not be held while
a service is stopped or the lock of this
+ // pool is taken (the stop of this pool holds that lock and clears the
cache)
+ private final Queue<SinglePool> evictedToStop = new
ConcurrentLinkedQueue<>();
private final int capacity;
private final Map<S, S> cache;
private interface Pool<S> {
+ /**
+ * Acquires a service, or returns null when the pool was evicted or
stopped meanwhile (single pool only)
+ */
S acquire() throws Exception;
- void release(S s);
+ /**
+ * Acquires the given service again if it is still the service of this
pool (single pool only)
+ */
+ boolean reacquire(S s);
+
+ /**
+ * Releases the service, or returns false when it is not a service of
this pool (single pool only)
+ */
+ boolean release(S s);
int size();
@@ -81,24 +101,22 @@ abstract class ServicePool<S extends Service> extends
ServiceSupport implements
}
/**
- * This callback is invoked by LRUCache from a separate background cleanup
thread. Therefore, we mark the entries to
- * be evicted from this thread only, and then let SinglePool and MultiPool
handle the evictions (stop the
- * producer/consumer safely) when they are acquiring/releases
producers/consumers. If we stop the producer/consumer
- * from the LRUCache background thread we can have a race condition with a
pooled producer may have been acquired at
- * the same time its being evicted.
+ * This callback is invoked by LRUCache when it evicts a service, which
may be in use at the same time. Therefore,
+ * the pools do not stop a service that is in use: SinglePool takes its
(shared) service out of use at once, and
+ * stops it when its last user releases it (or after the cache operation,
see {@link #stopEvictedPools()}, when it
+ * is idle), and MultiPool stops an evicted service when it is idle, on
acquire or release.
*/
protected void onEvict(S s) {
Endpoint e = getEndpoint.apply(s);
Pool<S> p = pool.get(e);
if (p != null) {
p.evict(s);
- if (capacity > 0 && pool.size() > capacity) {
- // the pool is growing too large, so we need to stop (stop
will remove itself from pool)
- p.stop();
- }
} else if (e.isSingletonProducer()) {
- // service no longer in a pool (such as being released twice, or
can happen during shutdown of Camel etc)
- stopAndRemove(s);
+ if (!singlePoolEvicted.containsKey(s)) {
+ // service no longer in a pool (such as being released twice,
or can happen during shutdown of Camel etc)
+ stopAndRemove(s);
+ }
+ // otherwise its pool was evicted while it is in use, and stops it
when it is released
} else {
// no pool for this endpoint (for example it was stopped, which
stopped its idle services, or the
// endpoint of the service is not the instance used as the pool
key): do not stop the service here, as it
@@ -114,16 +132,50 @@ abstract class ServicePool<S extends Service> extends
ServiceSupport implements
* @return the acquired producer/consumer
*/
public S acquire(Endpoint endpoint) throws Exception {
- if (!isStarted()) {
- return null;
+ S s = null;
+ while (s == null) {
+ if (!isStarted()) {
+ return null;
+ }
+ // a single pool returns null when it was evicted or stopped
meanwhile, and is then no longer in the pool
+ // map, so a new pool is used
+ s = getOrCreatePool(endpoint).acquire();
}
- S s = getOrCreatePool(endpoint).acquire();
- if (s != null && cache != null) {
- cache.putIfAbsent(s, s);
+ if (cache != null) {
+ try {
+ cache.putIfAbsent(s, s);
+ } finally {
+ stopEvictedPools();
+ }
}
return s;
}
+ /**
+ * Stops the services of the single pools that the LRU cache has evicted,
if they are idle (otherwise their last
+ * release stops them). Called after each operation on the cache, by the
thread that did it (the one that evicts),
+ * as the cache calls onEvict under its write lock: a slow stop there
would hold up every acquire of this pool, and
+ * the stop of the endpoint takes the lock of this pool, which its stop
holds while it clears the cache.
+ */
+ private void stopEvictedPools() {
+ for (SinglePool p = evictedToStop.poll(); p != null; p =
evictedToStop.poll()) {
+ p.stopEvicted();
+ }
+ }
+
+ /**
+ * Acquires the given singleton producer/consumer again, which was
acquired before, if it is still pooled (it has
+ * not been evicted or stopped meanwhile). It must be released as when it
is acquired with
+ * {@link #acquire(Endpoint)}.
+ *
+ * @param s the producer/consumer
+ * @return true if it was acquired again, false if it is no longer pooled
+ */
+ boolean reacquire(S s) {
+ Pool<S> p = pool.get(getEndpoint.apply(s));
+ return p != null && p.reacquire(s);
+ }
+
/**
* Releases the producer/consumer back to the pool
*
@@ -132,14 +184,24 @@ abstract class ServicePool<S extends Service> extends
ServiceSupport implements
*/
public void release(Endpoint endpoint, S s) {
Pool<S> p = pool.get(endpoint);
- if (p != null) {
- p.release(s);
- } else {
- // the pool was evicted while this service was in use
+ if (p != null && p.release(s)) {
+ return;
+ }
+ // the pool was evicted while this service was in use (the endpoint
may have a new pool meanwhile)
+ p = singlePoolEvicted.get(s);
+ if (p == null || !p.release(s)) {
stopAndRemove(s);
}
}
+ /**
+ * Called by a single pool when it has acquired its service, before it
returns it. A test hook (noop): a test pauses
+ * here to evict the service while it is being acquired.
+ */
+ void onSingleAcquired(S s) {
+ // noop
+ }
+
private void stopAndRemove(S s) {
ServicePool.stop(s);
try {
@@ -174,8 +236,12 @@ abstract class ServicePool<S extends Service> extends
ServiceSupport implements
* Cleanup the pool (removing stale instances that should be evicted)
*/
public void cleanUp() {
- if (cache instanceof LRUCache lru) {
- lru.cleanUp();
+ try {
+ if (cache instanceof LRUCache lru) {
+ lru.cleanUp();
+ }
+ } finally {
+ stopEvictedPools();
}
pool.values().forEach(Pool::cleanUp);
}
@@ -234,10 +300,23 @@ abstract class ServicePool<S extends Service> extends
ServiceSupport implements
/**
* Pool used for singleton producers or consumers which are thread-safe
and can be shared by multiple worker threads
* at any given time.
+ * <p>
+ * The pool counts the users of its service (acquired and not yet
released), so an evicted service is stopped when
+ * it is no longer in use. An evicted pool is taken out of the pool map at
once, so the next acquire of the endpoint
+ * creates a new pool and service.
*/
private class SinglePool implements Pool<S> {
private final Endpoint endpoint;
private volatile S s;
+ // the acquires and the releases of s, counted apart without
contention between the worker threads (the users of
+ // s are the difference). An increment of a LongAdder is only a
release write, which a later read of evicted may
+ // pass, so retain() and unretain() have a full fence between them:
either the user sees evicted, or the
+ // eviction (which writes evicted before it sums the counts) sees the
increment
+ private final LongAdder acquires = new LongAdder();
+ private final LongAdder releases = new LongAdder();
+ // s has been evicted: it is no longer handed out, and is stopped when
it has no more users
+ private volatile boolean evicted;
+ private final AtomicBoolean stopped = new AtomicBoolean();
SinglePool(Endpoint endpoint) {
this.endpoint = requireNonNull(endpoint);
@@ -245,31 +324,73 @@ abstract class ServicePool<S extends Service> extends
ServiceSupport implements
@Override
public S acquire() throws Exception {
- cleanupEvicts();
-
- if (s == null) {
+ if (!retain()) {
+ return null;
+ }
+ S answer = s;
+ if (answer == null) {
+ boolean acquired = false;
lock.lock();
try {
- if (s == null) {
+ answer = s;
+ if (answer == null && !stopped.get()) {
LOG.trace("Creating service from endpoint: {}",
endpoint);
S tempS = creator.apply(endpoint);
+ if (tempS == null) {
+ // fail as main did, as a null would make
ServicePool.acquire retry this pool for ever: it
+ // retries only when the pool was evicted or
stopped meanwhile
+ throw new IllegalStateException("No service
created from endpoint: " + endpoint);
+ }
endpoint.getCamelContext().addService(tempS, true,
true);
s = tempS;
+ answer = tempS;
}
+ acquired = answer != null;
} finally {
lock.unlock();
+ if (!acquired) {
+ // creating failed, or the pool was stopped meanwhile
+ unretain();
+ }
}
}
- LOG.trace("Acquired service: {}", s);
- return s;
+ onSingleAcquired(answer);
+ LOG.trace("Acquired service: {}", answer);
+ return answer;
}
@Override
- public void release(S s) {
- cleanupEvicts();
+ public boolean reacquire(S s) {
+ return s != null && s == this.s && retain();
+ }
- // noop
+ @Override
+ public boolean release(S s) {
+ if (s == null || s != this.s) {
+ return false;
+ }
+ unretain();
LOG.trace("Released service: {}", s);
+ return true;
+ }
+
+ private boolean retain() {
+ acquires.increment();
+ VarHandle.fullFence();
+ if (evicted || stopped.get()) {
+ // evicted or stopped meanwhile (the eviction may have counted
this acquire already, so it is released)
+ unretain();
+ return false;
+ }
+ return true;
+ }
+
+ private void unretain() {
+ releases.increment();
+ VarHandle.fullFence();
+ if (evicted) {
+ stopEvicted();
+ }
}
@Override
@@ -279,44 +400,93 @@ abstract class ServicePool<S extends Service> extends
ServiceSupport implements
@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)) {
+ // still in use (the last user stops it), or stopped already
+ return;
+ }
+ S toStop = takeService();
+ if (toStop != null) {
+ singlePoolEvicted.remove(toStop, this);
+ }
+ // stop the evicted service first, so it no longer counts as using
the endpoint; outside the lock, so a slow
+ // stop does not hold up the creation of the services of other
endpoints
+ doStop(toStop);
+ stopEndpointIfUnused();
}
- private void cleanupEvicts() {
- if (!singlePoolEvicted.isEmpty()) {
- for (Map.Entry<Endpoint, Pool<S>> entry :
singlePoolEvicted.entrySet()) {
- Endpoint e = entry.getKey();
- Pool<S> p = entry.getValue();
- // stop the evicted service first, so it no longer counts
as using the endpoint
- p.stop();
- if (!isEndpointInUse(e)) {
- // stop the endpoint as well (such as a dynamic
endpoint from toD) to free its resources
- doStop(e);
- }
- singlePoolEvicted.remove(e);
+ /**
+ * Stops the endpoint (such as a dynamic endpoint from toD) to free
its resources, if nothing else uses it.
+ * Under the lock that creates the services, so a service that a new
pool of this endpoint creates meanwhile is
+ * either seen as using the endpoint, or created after it was stopped.
+ */
+ private void stopEndpointIfUnused() {
+ lock.lock();
+ try {
+ if (!isEndpointInUse(endpoint)) {
+ doStop(endpoint);
}
+ } finally {
+ lock.unlock();
}
}
+ @Override
+ public void cleanUp() {
+ // noop: an evicted service is stopped after the cache operation
that evicted it, or by its last release
+ }
+
void doStop(Service s) {
if (s != null) {
ServicePool.stop(s);
@@ -368,7 +538,12 @@ abstract class ServicePool<S extends Service> extends
ServiceSupport implements
}
@Override
- public void release(S s) {
+ public boolean reacquire(S s) {
+ return false;
+ }
+
+ @Override
+ public boolean release(S s) {
cleanupEvicts();
if (stopped || !active.contains(s) || !queue.offer(s)) {
@@ -380,6 +555,7 @@ abstract class ServicePool<S extends Service> extends
ServiceSupport implements
active.remove(s);
doStop(s);
}
+ return true;
}
@Override
@@ -408,6 +584,10 @@ abstract class ServicePool<S extends Service> extends
ServiceSupport implements
cleanupEvicts();
}
}
+ if (capacity > 0 && pool.size() > capacity) {
+ // the pool is growing too large, so we need to stop (stop
will remove itself from pool)
+ stop();
+ }
}
@Override