From a0e5589c86dba44702b5bb77f269462371f0622c Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Wed, 25 Nov 2026 10:12:30 +0100 Subject: [PATCH 01/18] Fresh HTTP/2 and HTTP/3 client connections must be valid The expiration timestamp of an HTTP/2 or HTTP/3 client connection is only set when a stream closes: a freshly established connection reports itself expired until its first stream closes. The periodic expiry check of the connection pool masks it in practice; an eager check evicts and closes the connection before it serves its first stream. Set the expiration timestamp at creation for the HTTP/2 codec, HTTP/2 multiplex and HTTP/3 implementations. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../http/impl/http2/codec/Http2ClientConnectionImpl.java | 1 + .../http2/multiplex/Http2MultiplexClientConnection.java | 1 + .../core/http/impl/http3/Http3ClientConnection.java | 1 + .../src/test/java/io/vertx/tests/http/HttpTest.java | 9 +++++++++ 4 files changed, 12 insertions(+) diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2ClientConnectionImpl.java b/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2ClientConnectionImpl.java index 7905cc922c0..4caaa8fff0c 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2ClientConnectionImpl.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2ClientConnectionImpl.java @@ -71,6 +71,7 @@ public class Http2ClientConnectionImpl extends Http2ConnectionImpl implements Ht this.authority = authority; this.creationTimestamp = System.currentTimeMillis(); this.handler = connHandler; + recycle(); } @Override diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/http2/multiplex/Http2MultiplexClientConnection.java b/vertx-core/src/main/java/io/vertx/core/http/impl/http2/multiplex/Http2MultiplexClientConnection.java index 4faab4177e2..ae62450e4a4 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/http2/multiplex/Http2MultiplexClientConnection.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/http2/multiplex/Http2MultiplexClientConnection.java @@ -70,6 +70,7 @@ public Http2MultiplexClientConnection(Http2MultiplexHandler handler, this.evicted = false; this.decompressionSupported = decompressionSupported; this.creationTimestamp = System.currentTimeMillis(); + refresh(); } @Override diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/http3/Http3ClientConnection.java b/vertx-core/src/main/java/io/vertx/core/http/impl/http3/Http3ClientConnection.java index 9caa32b7f02..4090991de90 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/http3/Http3ClientConnection.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/http3/Http3ClientConnection.java @@ -66,6 +66,7 @@ public Http3ClientConnection(QuicConnectionInternal connection, this.keepAliveTimeoutMillis = keepAliveTimeoutMillis; this.creationTimestamp = System.currentTimeMillis(); this.concurrency = concurrency; + refresh(); } public void init() { diff --git a/vertx-core/src/test/java/io/vertx/tests/http/HttpTest.java b/vertx-core/src/test/java/io/vertx/tests/http/HttpTest.java index 4ad7fea9d46..7619e1007c1 100644 --- a/vertx-core/src/test/java/io/vertx/tests/http/HttpTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/http/HttpTest.java @@ -84,6 +84,15 @@ protected HttpTest(HttpConfigurator config) { super(config); } + @Test + public void testConnectionValidAfterConnect() throws Exception { + server.requestHandler(req -> req.response().end()); + startServer(testAddress); + HttpClientConnection conn = client.connect(new HttpConnectOptions().setServer(testAddress)).await(); + // A fresh connection must be valid: its keep-alive expiration starts at creation + assertTrue(((io.vertx.core.http.impl.UnpooledHttpClientConnection) conn).unwrap().isValid()); + } + @Test public void testCloseMulti() throws Exception { int num = 4; From 4c5f4ef7d588c85b6d52dde47bc7eacac44030e6 Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Tue, 1 Dec 2026 11:27:11 +0100 Subject: [PATCH 02/18] Fix the clear text upgrade resolution signals Motivation: The codec client channel initializer handles a successful clear text upgrade by falling through the rejected case: UpgradeResult's upgradeRejected is signalled on success as a pipeline cleanup and sets the upgrade processed flag, polluting the rejection semantics. The multiplex initializer signals the rejection only on rejection, so a successful multiplex upgrade never marks the upgrade processed: the upgraded connection reports a concurrency of one. Changes: A successful upgrade marks the upgrade processed when the upgraded connection is swapped in; the codec initializer separates the successful case - the pipeline cleanup - from the rejected case - the rejection signal. A successfully upgraded connection reports the HTTP/2 concurrency. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../codec/Http2CodecClientChannelInitializer.java | 6 ++++-- .../impl/tcp/Http2UpgradeClientConnection.java | 1 + .../test/java/io/vertx/tests/http/Http2Test.java | 15 +++++++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2CodecClientChannelInitializer.java b/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2CodecClientChannelInitializer.java index 107079fb19e..cc9856fc07d 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2CodecClientChannelInitializer.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2CodecClientChannelInitializer.java @@ -132,11 +132,13 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc case UPGRADE_SUCCESSFUL: // Remove Http1xClientConnection handler pipeline.remove("handler"); - // Go through + // Remove this handler + // Upgrade handler will remove itself and remove the HttpClientCodec + pipeline.remove(this); + break; case UPGRADE_REJECTED: // Remove this handler pipeline.remove(this); - // Upgrade handler will remove itself and remove the HttpClientCodec result.upgradeRejected(); break; } diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/tcp/Http2UpgradeClientConnection.java b/vertx-core/src/main/java/io/vertx/core/http/impl/tcp/Http2UpgradeClientConnection.java index 277b24cc20e..51c76708a26 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/tcp/Http2UpgradeClientConnection.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/tcp/Http2UpgradeClientConnection.java @@ -348,6 +348,7 @@ void handleUpgrade(io.vertx.core.http.impl.HttpClientConnection conn, HttpClient pushHandler = null; closeHandler = null; upgradedConnection.current = conn; + upgradedConnection.upgradeProcessed = true; conn.closeHandler(upgradedConnection.closeHandler); conn.exceptionHandler(upgradedConnection.exceptionHandler); conn.pingHandler(upgradedConnection.pingHandler); diff --git a/vertx-core/src/test/java/io/vertx/tests/http/Http2Test.java b/vertx-core/src/test/java/io/vertx/tests/http/Http2Test.java index 0358b435bcc..24af4d5f18c 100644 --- a/vertx-core/src/test/java/io/vertx/tests/http/Http2Test.java +++ b/vertx-core/src/test/java/io/vertx/tests/http/Http2Test.java @@ -707,6 +707,21 @@ public void testStreamWeightAndDependencyInheritancePushPromise(Checkpoint check .await(); } + @Test + public void testClearTextUpgradeConnectionConcurrency() throws Exception { + server = vertx.createHttpServer(); + server.requestHandler(req -> req.response().end()); + startServer(testAddress); + client = vertx.createHttpClient(new HttpClientOptions().setProtocolVersion(HttpVersion.HTTP_2)); + HttpClientConnection conn = client.connect(new HttpConnectOptions().setServer(testAddress).setSsl(false)).await(); + // The upgrade rides on the first request + conn.request(new RequestOptions(requestOptions).setSsl(false)) + .compose(req -> req.send().compose(HttpClientResponse::end)) + .await(); + // A successfully upgraded connection reports the HTTP/2 concurrency + assertTrue(((io.vertx.core.http.impl.UnpooledHttpClientConnection) conn).unwrap().concurrency() > 1); + } + @Test public void testClearTextUpgradeWithBody() throws Exception { server = vertx.createHttpServer().requestHandler(req -> { From c62f6cec11f2e71c2a673f4635e0e1391f7fac09 Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Wed, 25 Nov 2026 14:40:22 +0100 Subject: [PATCH 03/18] Remove unused SimpleConnectionPool members Motivation: LazyFuture and the POOL_CLOSED future are not used anymore. Changes: Remove them. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../internal/pool/SimpleConnectionPool.java | 76 ------------------- 1 file changed, 76 deletions(-) diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/SimpleConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/SimpleConnectionPool.java index 6f65cd9a948..782a3dbf891 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/SimpleConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/SimpleConnectionPool.java @@ -75,7 +75,6 @@ */ public class SimpleConnectionPool implements ConnectionPool { - private static final Future POOL_CLOSED = Future.failedFuture("Pool closed"); private static final VertxException POOL_CLOSED_EXCEPTION = new VertxException("Pool closed", true); /** @@ -923,79 +922,4 @@ public int size() { return size; } } - - static class LazyFuture extends io.vertx.core.impl.future.FutureBase implements Promise { - - private final List> handlers = new ArrayList<>(); - private Future fut = null; - - @Override - public boolean tryComplete(T result) { - handle(Future.succeededFuture(result)); - return true; - } - - @Override - public boolean tryFail(Throwable cause) { - handle(Future.failedFuture(cause)); - return true; - } - - @Override - public Future future() { - return this; - } - - @Override - public void handle(AsyncResult event) { - Future f = (Future) event; - List> h; - synchronized (this) { - fut = f; - h = handlers; - } - for (Completable t : h) { - t.complete(event.result(), event.cause()); - } - } - - @Override - public synchronized boolean isComplete() { - return fut != null && fut.isComplete(); - } - @Override - public synchronized T result() { - return fut != null ? fut.result() : null; - } - @Override - public Throwable cause() { - return fut != null ? fut.cause() : null; - } - @Override - public boolean succeeded() { - return fut != null && fut.succeeded(); - } - @Override - public boolean failed() { - return fut != null && fut.failed(); - } - @Override - public void addListener(Completable listener) { - Future f; - synchronized (this) { - f = fut; - if (f == null) { - handlers.add(listener); - return; - } - } - listener.complete(f.result(), f.cause()); - } - @Override - public void removeListener(Completable listener) { - synchronized (this) { - handlers.remove(listener); - } - } - } } From 964878629f98e824b6b099b6e5a90d3877d8af83 Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Tue, 24 Nov 2026 13:55:16 +0100 Subject: [PATCH 04/18] Introduce DefaultConnectionPool as a copy of SimpleConnectionPool Motivation: Reimplement the connection pool state machine declaratively: actions record state changes and a single method progresses the pool toward its desired state. Starting from a verbatim copy, each subsequent change reviews as a plain diff against SimpleConnectionPool. Changes: Copy SimpleConnectionPool to DefaultConnectionPool, construction exposed by pool(...) static factories and a builder. Route pool construction in ConnectionPoolTest through overridable methods and run the same suite against the new implementation with DefaultConnectionPoolTest. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../internal/pool/DefaultConnectionPool.java | 963 ++++++++++++++++++ .../vertx/tests/pool/ConnectionPoolTest.java | 84 +- .../tests/pool/DefaultConnectionPoolTest.java | 28 + 3 files changed, 1037 insertions(+), 38 deletions(-) create mode 100644 vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java create mode 100644 vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java new file mode 100644 index 00000000000..5e1a61c7836 --- /dev/null +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java @@ -0,0 +1,963 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ +package io.vertx.core.internal.pool; + +import io.vertx.core.*; +import io.vertx.core.http.ConnectionPoolTooBusyException; +import io.vertx.core.internal.ContextInternal; + +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; + +/** + *

The pool is a state machine that maintains a queue of waiters and a list of connections. + * + *

Pool state

+ * + *

Interactions with the pool modifies the pool state and then the pool executes actions to make progress satisfying + * the pool requests. + * + *

The pool is implemented as a non blocking state machine. + * + *

Calls to the pool are serialized to avoid race conditions and maintain its invariants. This pool can + * be called from different threads safely. The pool state is mutated exclusively by {@link Executor.Action} and actions are serialized + * by the executor. + * + *

Pool capacity

+ * + * To constrain the number of connections the pool maintains a {@link #capacity} field that must remain lesser than + * {@link #maxCapacity} to create a connection. Such capacity is used instead of counting connection because the pool + * can mix connections with different concurrency (HTTP/1 and HTTP/2) and this flexibility is necessary. + * + *

Pool connector

+ * + * The pool interacts with connections with the {@link PoolConnector}. The {@link PoolConnector.Listener} + * let the connector interact with pool: + *
    + *
  • The connector can remove connections from the pool using {@link PoolConnector.Listener#onRemove()}.
  • + *
  • The connector can signal the change of the connection capacity using {@link PoolConnector.Listener#onConcurrencyChange(long)}.
  • + *
+ * + *

Connection eviction

+ * + * Connections can be evicted from the pool with {@link ConnectionPool#evict(Predicate)}. It + * can be used to implement keep alive timeout. + * + *

Waiter lifecycle

+ * + * Connection requests are done with {@link ConnectionPool#acquire(ContextInternal, int)}. Such request + * creates a {@link PoolWaiter}. When such request is made + * + *
    + *
  • the waiter can be handed back a connection when one is immediately available
  • + *
  • a connection can be created and then handed back to the waiter that initiated the action
  • + *
  • the waiter can be enqueued when the pool is full and the wait queue is not full
  • + *
  • the waiter can be failed
  • + *
+ * + * A connection acquisition a {@link PoolWaiter.Listener} can be provided, letting the requester + * to get a reference on the waiter and later use {@link #cancel(PoolWaiter)} to cancel + * a request. + */ +public class DefaultConnectionPool implements ConnectionPool { + + private static final VertxException POOL_CLOSED_EXCEPTION = new VertxException("Pool closed", true); + + /** + * Select the first available available connection with the same event loop. + */ + private static final BiFunction, PoolConnection> SAME_EVENT_LOOP_SELECTOR = (waiter, list) -> { + int size = list.size(); + for (int i = 0;i < size;i++) { + PoolConnection slot = list.get(i); + if (slot.context().nettyEventLoop() == waiter.context().nettyEventLoop() && slot.available() > 0) { + return slot; + } + } + return null; + }; + + /** + * Select the first available connection. + */ + private static final BiFunction, PoolConnection> FIRST_AVAILABLE_SELECTOR = (waiter, list) -> { + int size = list.size(); + for (int i = 0;i < size;i++) { + PoolConnection slot = list.get(i); + if (slot.available() > 0) { + return slot; + } + } + return null; + }; + + /** + * A slot for a connection. + */ + static class Slot implements PoolConnector.Listener, PoolConnection { + + private final DefaultConnectionPool pool; + private final ContextInternal context; + private final Promise result; + private PoolWaiter initiator; + private C connection; // The actual connection, might be null + private int index; // The index in the pool slots array + private int usage; // The number of times this connection is acquired + private long concurrency; // The total number of times the connection can be acquired + private int capacity; // The connection capacity + + public Slot(DefaultConnectionPool pool, ContextInternal context, int index, int capacity) { + this.pool = pool; + this.context = context; + this.connection = null; + this.usage = 0; + this.index = index; + this.capacity = capacity; + this.result = context.promise(); + } + + @Override + public void onRemove() { + pool.remove(this); + } + + @Override + public void onConcurrencyChange(long concurrency) { + pool.setConcurrency(this, concurrency); + } + + @Override + public ContextInternal context() { + return context; + } + + @Override + public C get() { + return connection; + } + + @Override + public int usage() { + return usage; + } + + @Override + public long available() { + return concurrency - usage; + } + + @Override + public long concurrency() { + return concurrency; + } + } + + private final PoolConnector connector; + private final int maxWaiters; + private final int maxCapacity; + private final int[] capacityFactors; + private final Executor> sync; + private final ListImpl list = new ListImpl(); + + // Whether the pool is closed + private boolean closed; + + // Selectors + private BiFunction, List>, PoolConnection> selector; + private Function contextProvider; + private BiFunction, List>, PoolConnection> fallbackSelector; + + // Connection state + private final Slot[] slots; // The pool connections, this array is not sparse + private int size; // The number of non null slots + private int capacity; // The pool capacity + + // The waiters + private final Waiters waiters; + private int requests; + + public static DefaultConnectionPool pool(PoolConnector connector, int[] maxSizes) { + return new DefaultConnectionPool<>(connector, maxSizes); + } + + public static DefaultConnectionPool pool(PoolConnector connector, int[] maxSizes, int maxWaiters) { + return new DefaultConnectionPool<>(connector, maxSizes, maxWaiters); + } + + public static Builder builder(PoolConnector connector) { + return new Builder<>(connector); + } + + public static class Builder { + + private final PoolConnector connector; + private int[] maxSizes; + private int maxWaiters = -1; + + Builder(PoolConnector connector) { + this.connector = Objects.requireNonNull(connector); + } + + public Builder withMaxSizes(int[] maxSizes) { + this.maxSizes = maxSizes; + return this; + } + + public Builder withMaxWaiters(int maxWaiters) { + this.maxWaiters = maxWaiters; + return this; + } + + public DefaultConnectionPool build() { + return new DefaultConnectionPool<>(connector, Objects.requireNonNull(maxSizes), maxWaiters); + } + } + + DefaultConnectionPool(PoolConnector connector, int[] maxSizes) { + this(connector, maxSizes, -1); + } + + DefaultConnectionPool(PoolConnector connector, int[] maxSizes, int maxWaiters) { + + int[] capacities = new int[maxSizes.length]; + int maxCapacity = 1; + int numSlots = 0; + for (int i = 0;i < maxSizes.length;i++) { + int maxSize = maxSizes[i]; + if (maxSize < 1) { + throw new IllegalArgumentException(); + } + maxCapacity *= maxSize; + numSlots = Math.max(numSlots, maxSize); + } + for (int i = 0;i < maxSizes.length;i++) { + capacities[i] = maxCapacity / maxSizes[i]; + } + + this.capacityFactors = capacities; + this.connector = connector; + this.slots = new Slot[numSlots]; + this.size = 0; + this.maxWaiters = maxWaiters; + this.capacity = 0; + this.maxCapacity = maxCapacity; + this.sync = new CombinerExecutor<>(this); + this.selector = (BiFunction) SAME_EVENT_LOOP_SELECTOR; + this.fallbackSelector = (BiFunction) FIRST_AVAILABLE_SELECTOR; + this.contextProvider = EVENT_LOOP_CONTEXT_PROVIDER; + this.waiters = new Waiters<>(); + } + + @Override + public ConnectionPool connectionSelector(BiFunction, List>, PoolConnection> selector) { + this.selector = selector; + return this; + } + + @Override + public ConnectionPool contextProvider(Function contextProvider) { + this.contextProvider = contextProvider; + return this; + } + + private void execute(Executor.Action> action) { + sync.submit(action); + } + + public int size() { + return size; + } + + public void connect(Slot slot, PoolWaiter waiter) { + slot.initiator = waiter; + connector.connect(slot.context, slot).onComplete(ar -> { + slot.initiator = null; + if (ar.succeeded()) { + execute(new ConnectSuccess<>(slot, ar.result(), waiter)); + } else { + execute(new ConnectFailed<>(slot, ar.cause(), waiter)); + } + }); + } + + private static class ConnectSuccess implements Executor.Action> { + + private final Slot slot; + private final ConnectResult result; + private PoolWaiter waiter; + + private ConnectSuccess(Slot slot, ConnectResult result, PoolWaiter waiter) { + this.slot = slot; + this.result = result; + this.waiter = waiter; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + + int capacity = pool.capacityFactors[(int)result.weight()]; + + int initialCapacity = slot.capacity; + slot.connection = result.connection(); + slot.concurrency = result.concurrency(); + slot.capacity = capacity; + slot.usage = 0; + pool.requests--; + pool.capacity += (capacity - initialCapacity); + if (pool.closed) { + if (waiter.disposed) { + waiter = null; + } else { + waiter.disposed = true; + } + return new Task() { + @Override + public void run() { + if (waiter != null) { + Future> fut = slot.context.failedFuture("Pool closed"); + fut.onComplete(waiter.handler); + } + slot.result.complete(slot.connection); + } + }; + } else { + long acquisitions = slot.concurrency; + if (acquisitions == 0) { + if (!waiter.disposed) { + pool.waiters.addFirst(waiter); + } + return null; + } + LeaseImpl lease; + int c; + if (waiter.disposed) { + lease = null; + c = 0; + } else { + lease = new LeaseImpl<>(slot, waiter.handler); + c = 1; + waiter.disposed = true; + acquisitions--; + } + LeaseImpl[] leases; + int m = (int)Math.min(acquisitions, pool.waiters.size()); + if (m > 0) { + c += m; + leases = new LeaseImpl[m]; + for (int i = 0;i < m;i++) { + PoolWaiter w = pool.waiters.poll(); + w.disposed = true; + leases[i] = new LeaseImpl<>(slot, w.handler); + } + } else { + leases = null; + } + slot.usage = c; + return new Task() { + @Override + public void run() { + if (lease != null) { + lease.emit(); + } + if (leases != null) { + for (LeaseImpl lease : leases) { + lease.emit(); + } + } + slot.result.complete(slot.connection); + } + }; + } + } + } + + private static class ConnectFailed implements Executor.Action> { + + private final Slot removed; + private final Throwable cause; + private PoolWaiter waiter; + + public ConnectFailed(Slot removed, Throwable cause, PoolWaiter waiter) { + this.removed = removed; + this.cause = cause; + this.waiter = waiter; + } + + public Task execute(DefaultConnectionPool pool) { + pool.requests--; + if (waiter.disposed) { + waiter = null; + } else { + waiter.disposed = true; + } + Task task = new Task() { + @Override + public void run() { + if (waiter != null) { + Throwable waiterFailure; + if (pool.closed) { + waiterFailure = POOL_CLOSED_EXCEPTION; + } else { + waiterFailure = cause; + } + waiter.handler.fail(waiterFailure); + } + removed.result.fail(cause); + } + }; + if (!pool.closed) { + Task removeTask = new Remove<>(removed).execute(pool); + if (removeTask != null) { + removeTask.next(task); + task = removeTask; + } + } + return task; + } + } + + private static class Remove implements Executor.Action> { + + protected final Slot removed; + + private Remove(Slot removed) { + this.removed = removed; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (pool.closed || pool.slots[removed.index] != removed) { + return null; + } + int w = removed.capacity; + removed.usage = 0; + removed.concurrency = 0; + removed.connection = null; + removed.capacity = 0; + PoolWaiter waiter = pool.waiters.poll(); + if (waiter != null) { + ContextInternal connectionContext = pool.contextProvider.apply(waiter.context); + Slot slot = new Slot<>(pool, connectionContext, removed.index, waiter.capacity); + pool.capacity -= w; + pool.capacity += waiter.capacity; + pool.slots[removed.index] = slot; + pool.requests++; + return new Task() { + @Override + public void run() { + if (waiter.listener != null) { + waiter.listener.onConnect(waiter); + } + pool.connect(slot, waiter); + } + }; + } else if (pool.size > 1) { + Slot tmp = pool.slots[pool.size - 1]; + tmp.index = removed.index; + pool.slots[removed.index] = tmp; + pool.slots[pool.size - 1] = null; + pool.size--; + pool.capacity -= w; + return null; + } else { + pool.slots[0] = null; + pool.size--; + pool.capacity -= w; + return null; + } + } + } + + private static class SetConcurrency implements Executor.Action> { + + private final Slot slot; + private final long concurrency; + + SetConcurrency(Slot slot, long concurrency) { + this.slot = slot; + this.concurrency = concurrency; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (slot.connection != null) { + long diff = concurrency - slot.concurrency; + slot.concurrency += diff; + if (diff > 0) { + LeaseImpl[] extra; + int m = (int)Math.min(slot.concurrency - slot.usage, pool.waiters.size()); + if (m > 0) { + extra = new LeaseImpl[m]; + for (int i = 0;i < m;i++) { + PoolWaiter w = pool.waiters.poll(); + w.disposed = true; + extra[i] = new LeaseImpl<>(slot, w.handler); + } + slot.usage += m; + return new Task() { + @Override + public void run() { + for (LeaseImpl lease : extra) { + lease.emit(); + } + } + }; + } else { + return null; + } + } else { + return null; + } + } else { + return null; + } + } + } + + private void setConcurrency(Slot slot, long concurrency) { + execute(new SetConcurrency<>(slot, concurrency)); + } + + private void remove(Slot removed) { + execute(new Remove<>(removed)); + } + + private static class Evict implements Executor.Action> { + + private final Predicate predicate; + private final Completable> handler; + + public Evict(Predicate predicate, Completable> handler) { + this.predicate = predicate; + this.handler = handler; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (pool.closed) { + return new Task() { + @Override + public void run() { + handler.fail(POOL_CLOSED_EXCEPTION); + } + }; + } + List res = new ArrayList<>(); + List> removed = new ArrayList<>(); + for (int i = pool.size - 1;i >= 0;i--) { + Slot slot = pool.slots[i]; + if (slot.connection != null && slot.usage == 0 && predicate.test(slot.connection)) { + removed.add(slot); + res.add(slot.connection); + } + } + Task head = new Task() { + @Override + public void run() { + handler.succeed(res); + } + }; + Task tail = head; + for (Slot slot : removed) { + Task next = new Remove<>(slot).execute(pool); + if (next != null) { + tail.next(next); + tail = next; + } + } + return head; + } + } + + @Override + public void evict(Predicate predicate, Completable> handler) { + execute(new Evict<>(predicate, handler)); + } + + private static class Acquire extends PoolWaiter implements Executor.Action> { + + public Acquire(ContextInternal context, PoolWaiter.Listener listener, int capacity, Completable> handler) { + super(listener, context, capacity, handler); + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (pool.closed) { + return new Task() { + @Override + public void run() { + Future> fut = context.failedFuture("Pool closed"); + fut.onComplete(handler); + } + }; + } + + // 1. Try reuse a existing connection with the same context + Slot slot1 = (Slot) pool.selector.apply(this, pool.list); + if (slot1 != null) { + slot1.usage++; + LeaseImpl lease = new LeaseImpl<>(slot1, handler); + return new Task() { + @Override + public void run() { + lease.emit(); + } + }; + } + + // 2. Try create connection + if (pool.capacity < pool.maxCapacity) { + pool.capacity += capacity; + ContextInternal connectionContext = pool.contextProvider.apply(context); + Slot slot2 = new Slot<>(pool, connectionContext, pool.size, capacity); + pool.slots[pool.size++] = slot2; + pool.requests++; + return new Task() { + @Override + public void run() { + if (listener != null) { + listener.onConnect(Acquire.this); + } + pool.connect(slot2, Acquire.this); + } + }; + } + + // 3. Try use another context + Slot slot3 = (Slot) pool.fallbackSelector.apply(this, pool.list); + if (slot3 != null) { + slot3.usage++; + LeaseImpl lease = new LeaseImpl<>(slot3, handler); + return new Task() { + @Override + public void run() { + lease.emit(); + } + }; + } + + // 4. Fall in waiters list + if (pool.maxWaiters == -1 || (pool.waiters.size() + pool.requests) < pool.maxWaiters) { + pool.waiters.addLast(this); + if (listener != null) { + return new Task() { + @Override + public void run() { + listener.onEnqueue(Acquire.this); + } + }; + } else { + return null; + } + } else { + return new Task() { + @Override + public void run() { + Future> fut = context.failedFuture(new ConnectionPoolTooBusyException("Connection pool reached max wait queue size of " + pool.maxWaiters)); + fut.onComplete(handler); + } + }; + } + } + } + + @Override + public void acquire(ContextInternal context, int kind, Completable> handler) { + execute(new Acquire<>(context, PoolWaiter.NULL_LISTENER, capacityFactors[kind], handler)); + } + + @Override + public void acquire(ContextInternal context, PoolWaiter.Listener listener, int kind, Completable> handler) { + execute(new Acquire<>(context, listener, capacityFactors[kind], handler)); + } + + @Override + public void cancel(PoolWaiter waiter, Completable handler) { + execute(new Cancel<>(waiter, handler)); + } + + private static class Cancel extends Task implements Executor.Action> { + + private final PoolWaiter waiter; + private final Completable handler; + private boolean cancelled; + + public Cancel(PoolWaiter waiter, Completable handler) { + this.waiter = waiter; + this.handler = handler; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (pool.closed) { + return new Task() { + @Override + public void run() { + handler.fail(POOL_CLOSED_EXCEPTION); + } + }; + } + if (pool.waiters.remove(waiter)) { + cancelled = true; + waiter.disposed = true; + } else if (!waiter.disposed) { + waiter.disposed = true; + cancelled = true; + } else { + cancelled = false; + } + return this; + } + + @Override + public void run() { + handler.succeed(cancelled); + } + } + + static class LeaseImpl implements Lease { + + private final Completable> handler; + private final Slot slot; + private final C connection; + private boolean recycled; + + public LeaseImpl(Slot slot, Completable> handler) { + this.handler = handler; + this.slot = slot; + this.connection = slot.connection; + } + + @Override + public C get() { + return connection; + } + + @Override + public void recycle() { + slot.pool.recycle(this); + } + + void emit() { + Future> fut = slot.context.succeededFuture(this); + fut.onComplete(handler); + } + } + + private static class Recycle implements Executor.Action> { + + private final Slot slot; + + public Recycle(Slot slot) { + this.slot = slot; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (!pool.closed && slot.connection != null) { + PoolWaiter waiter; + if (slot.usage <= slot.concurrency && (waiter = pool.waiters.poll()) != null) { + waiter.disposed = true; + LeaseImpl lease = new LeaseImpl<>(slot, waiter.handler); + return new Task() { + @Override + public void run() { + lease.emit(); + } + }; + } else { + slot.usage--; + } + } + return null; + } + } + + private void recycle(LeaseImpl lease) { + if (lease.recycled) { + throw new IllegalStateException("Attempt to recycle more than permitted"); + } + lease.recycled = true; + execute(new Recycle<>(lease.slot)); + } + + public int waiters() { + return waiters.size(); + } + + public int capacity() { + return capacity; + } + + @Override + public int requests() { + return requests; + } + + private static class Close implements Executor.Action> { + + private final Completable>> handler; + + private Close(Completable>> handler) { + this.handler = handler; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (pool.closed) { + return new Task() { + @Override + public void run() { + handler.fail(POOL_CLOSED_EXCEPTION); + } + }; + } + pool.closed = true; + List> waiters = pool.waiters.clear(); + List> list = new ArrayList<>(); + for (int i = 0;i < pool.size;i++) { + Slot slot = pool.slots[i]; + pool.slots[i] = null; + PoolWaiter waiter = slot.initiator; + if (waiter != null) { + waiters.add(slot.initiator); + slot.initiator.disposed = true; + slot.initiator = null; + } + pool.capacity -= slot.capacity; + list.add(slot.result.future()); + } + pool.size = 0; + return new Task() { + @Override + public void run() { + waiters.forEach(w -> { + w.handler.fail(POOL_CLOSED_EXCEPTION); + }); + handler.succeed(list); + } + }; + } + } + + @Override + public void close(Completable>> handler) { + execute(new Close<>(handler)); + } + + private static class Waiters implements Iterable> { + + private final PoolWaiter head; + private int size; + + public Waiters() { + head = new PoolWaiter<>(null, null, 0, null); + head.next = head.prev = head; + } + + PoolWaiter poll() { + if (head.next == head) { + return null; + } + PoolWaiter node = head.next; + remove(node); + return node; + } + + void addLast(PoolWaiter node) { + if (node.queued) { + throw new IllegalStateException(); + } + node.queued = true; + node.prev = head.prev; + node.next = head; + head.prev.next = node; + head.prev = node; + size++; + } + + void addFirst(PoolWaiter node) { + if (node.queued) { + throw new IllegalStateException(); + } + node.queued = true; + node.prev = head; + node.next = head.next; + head.next.prev = node; + head.next = node; + size++; + } + + boolean remove(PoolWaiter node) { + if (!node.queued) { + return false; + } + node.next.prev = node.prev; + node.prev.next = node.next; + node.next = node.prev = null; + node.queued = false; + size--; + return true; + } + + List> clear() { + List> lst = new ArrayList<>(size); + this.forEach(lst::add); + size = 0; + head.next = head.prev = head; + return lst; + } + + int size() { + return size; + } + + @Override + public Iterator> iterator() { + return new Iterator>() { + PoolWaiter current = head; + @Override + public boolean hasNext() { + return current.next != head; + } + @Override + public PoolWaiter next() { + if (current.next == head) { + throw new NoSuchElementException(); + } + try { + return current.next; + } finally { + current = current.next; + } + } + }; + } + } + + class ListImpl extends AbstractList> { + @Override + public PoolConnection get(int index) { + return slots[index]; + } + @Override + public int size() { + return size; + } + } +} diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java index 9de5253ccbe..d09d4a4ca8f 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java @@ -48,11 +48,19 @@ public void setUp() throws Exception { this.vertx = (VertxInternal) super.vertx; } + protected ConnectionPool pool(PoolConnector connector, int[] maxSizes) { + return ConnectionPool.pool(connector, maxSizes); + } + + protected ConnectionPool pool(PoolConnector connector, int[] maxSizes, int maxWaiters) { + return ConnectionPool.pool(connector, maxSizes, maxWaiters); + } + @Test public void testConnect() { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 10 }, 10); + ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); Connection expected = new Connection(); pool .acquire(context, 0, TestUtils.onSuccess2(lease -> { @@ -71,7 +79,7 @@ public void testConnect() { public void testAcquireRecycledConnection() throws Exception { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 10 }); + ConnectionPool pool = pool(mgr, new int[] { 10 }); Connection expected = new Connection(); CountDownLatch latch = new CountDownLatch(1); pool @@ -94,7 +102,7 @@ public void testAcquireRecycledConnection() throws Exception { public void testRecycleRemovedConnection() throws Exception { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 10 }, 10); + ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); Connection expected1 = new Connection(); Future> fut = Future.future(p -> pool.acquire(context, 0, p)); ConnectionRequest request1 = mgr.assertRequest(); @@ -120,7 +128,7 @@ public void testRecycleRemovedConnection() throws Exception { public void testConcurrency() throws Exception { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 10 }, 10); + ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); Connection expected = new Connection(); CountDownLatch latch = new CountDownLatch(1); pool @@ -140,7 +148,7 @@ public void testConcurrency() throws Exception { @Test public void testIncreaseConcurrency() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); ContextInternal ctx = vertx.createEventLoopContext(); Connection conn1 = new Connection(); CountDownLatch l1 = new CountDownLatch(1); @@ -166,7 +174,7 @@ public void testIncreaseConcurrency() throws Exception { public void testSatisfyPendingWaitersWithExtraConcurrency() throws Exception { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 2); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 2); Connection expected = new Connection(); AtomicInteger seq = new AtomicInteger(); pool @@ -189,7 +197,7 @@ public void testSatisfyPendingWaitersWithExtraConcurrency() throws Exception { public void testEmptyConcurrency() { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 2); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 2); Connection expected = new Connection(); AtomicInteger seq = new AtomicInteger(); pool @@ -214,7 +222,7 @@ public void testEmptyConcurrency() { public void testEmptyConcurrencyWithManyWaiters() { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 3); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 3); Connection expected = new Connection(); AtomicInteger seq = new AtomicInteger(); for (int i = 0;i < 3;i++) { @@ -238,7 +246,7 @@ public void testEmptyConcurrencyWithManyWaiters() { @Test public void testDecreaseConcurrency() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); ContextInternal ctx = vertx.createEventLoopContext(); Connection conn1 = new Connection(); CountDownLatch l1 = new CountDownLatch(2); @@ -278,7 +286,7 @@ public void testDecreaseConcurrency() throws Exception { public void testWaiter() throws Exception { ContextInternal ctx1 = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); Connection expected = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); pool.acquire(ctx1, 0, TestUtils.onSuccess2(latch::complete)); @@ -303,7 +311,7 @@ public void testWaiter() throws Exception { public void testRemoveSingleConnection() throws Exception { ContextInternal ctx1 = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 1); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 1); Connection conn = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); pool.acquire(ctx1, 0, TestUtils.onSuccess2(latch::complete)); @@ -319,7 +327,7 @@ public void testRemoveSingleConnection() throws Exception { public void testRemoveFirstConnection() throws Exception { ContextInternal ctx = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 2 }, 2); + ConnectionPool pool = pool(mgr, new int[] { 2 }, 2); Connection conn1 = new Connection(); CompletableFuture> latch1 = new CompletableFuture<>(); pool.acquire(ctx, 0, TestUtils.onSuccess2(latch1::complete)); @@ -340,7 +348,7 @@ public void testRemoveFirstConnection() throws Exception { public void testRemoveSingleConnectionWithWaiter() throws Exception { ContextInternal ctx1 = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); Connection connection1 = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); pool @@ -370,7 +378,7 @@ public void testRemoveSingleConnectionWithWaiter() throws Exception { @Test public void testConnectFailureWithPendingWaiter() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1, 2 }, 2); + ConnectionPool pool = pool(mgr, new int[] { 1, 2 }, 2); Throwable failure = new Throwable(); Connection expected = new Connection(); CountDownLatch latch = new CountDownLatch(1); @@ -424,7 +432,7 @@ public void testExpireSome() throws Exception { private List testExpire(int num, int max, int... recycled) throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { max }, max); + ConnectionPool pool = pool(mgr, new int[] { max }, max); CountDownLatch latch = new CountDownLatch(num); List> leases = new ArrayList<>(); ContextInternal ctx = vertx.createEventLoopContext(); @@ -461,7 +469,7 @@ private List testExpire(int num, int max, int... recycled) throws Excep @Test public void testRemoveEvicted() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 1); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 1); // List> leases = new ArrayList<>(); ContextInternal ctx = vertx.createEventLoopContext(); CountDownLatch latch1 = new CountDownLatch(1); @@ -484,7 +492,7 @@ public void testRemoveEvicted() throws Exception { @Test public void testSynchronousEviction() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 1); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 1); ContextInternal ctx = vertx.createEventLoopContext(); CountDownLatch latch1 = new CountDownLatch(1); CountDownLatch latch2 = new CountDownLatch(1); @@ -520,7 +528,7 @@ public void testSynchronousEviction() throws Exception { @Test public void testConnectionInProgressShouldNotBeEvicted() { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 5); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 5); ContextInternal ctx = vertx.createEventLoopContext(); pool.acquire(ctx, 0, (res, err) -> {}); mgr.assertRequest(); @@ -535,7 +543,7 @@ public void testConnectionInProgressShouldNotBeEvicted() { @Test public void testRecycleRemoveConnection() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 1); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 1); Connection expected = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); ContextInternal ctx1 = vertx.createEventLoopContext(); @@ -552,7 +560,7 @@ public void testRecycleRemoveConnection() throws Exception { @Test public void testRecycleMultiple() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 1); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 1); Connection expected = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); ContextInternal ctx1 = vertx.createEventLoopContext(); @@ -571,7 +579,7 @@ public void testRecycleMultiple() throws Exception { @Test public void testMaxWaiters() { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 5); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 5); ContextInternal ctx = vertx.createEventLoopContext(); for (int i = 0;i < (5);i++) { pool @@ -588,7 +596,7 @@ public void testMaxWaiters() { @Test public void testHeterogeneousSizes() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 5, 2 }); + ConnectionPool pool = pool(mgr, new int[] { 5, 2 }); ContextInternal ctx = vertx.createEventLoopContext(); CountDownLatch latch = new CountDownLatch(5); for (int i = 0;i < 5;i++) { @@ -608,7 +616,7 @@ public void testHeterogeneousSizes() throws Exception { @Test public void testClose() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 2 }, 2); + ConnectionPool pool = pool(mgr, new int[] { 2 }, 2); ContextInternal ctx = vertx.createEventLoopContext(); Connection conn1 = new Connection(); pool @@ -632,7 +640,7 @@ public void testClose() throws Exception { public void testCloseTwice() throws Exception { AtomicBoolean isReentrant = new AtomicBoolean(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 2 }, 2); + ConnectionPool pool = pool(mgr, new int[] { 2 }, 2); CountDownLatch latch = new CountDownLatch(1); pool .close(TestUtils.onSuccess2(lst -> { @@ -651,7 +659,7 @@ public void testCloseTwice() throws Exception { public void testUseAfterClose() throws Exception { waitFor(3); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); ContextInternal ctx = vertx.createEventLoopContext(); CompletableFuture> waiterFut = new CompletableFuture<>(); pool.acquire(ctx, new PoolWaiter.Listener<>() { @@ -678,7 +686,7 @@ public void onConnect(PoolWaiter waiter) { @Test public void testAcquireClosedConnection() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); ContextInternal context = vertx.createEventLoopContext(); pool.acquire(context, 0, TestUtils.onSuccess2(Lease::recycle)); Connection expected = new Connection(); @@ -728,7 +736,7 @@ public void testConnectFailureAfterClose() { private void testConnectResultAfterClose(boolean success) { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); ContextInternal ctx = vertx.createEventLoopContext(); AtomicInteger acquired = new AtomicInteger(); pool @@ -763,7 +771,7 @@ public void testCancelQueuedWaiters() throws Exception { waitFor(1); ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); CompletableFuture> w = new CompletableFuture<>(); pool .acquire(context, 0, TestUtils.onSuccess2(lease -> { @@ -811,7 +819,7 @@ public void testCancelWaiterBeforeConnection(boolean success, int extra) throws waitFor(1); ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 1 + extra); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 1 + extra); CompletableFuture> waiterLatch = new CompletableFuture<>(); pool.acquire(context, new PoolWaiter.Listener<>() { @Override @@ -874,7 +882,7 @@ public void testCancelWaiterAfterConnectionSuccess(boolean success) throws Excep waitFor(1); ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 1); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 1); CompletableFuture> w = new CompletableFuture<>(); CountDownLatch latch = new CountDownLatch(1); pool.acquire(context, new PoolWaiter.Listener<>() { @@ -906,7 +914,7 @@ public void testCancelWaiterDispatchedByRecycle() throws Exception { waitFor(1); ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[]{1}); + ConnectionPool pool = pool(mgr, new int[]{1}); // Step 1: Acquire and establish a connection CountDownLatch connectedLatch = new CountDownLatch(1); @@ -946,7 +954,7 @@ public void testConnectionSelector() throws Exception { waitFor(1); ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 2 }); + ConnectionPool pool = pool(mgr, new int[] { 2 }); CountDownLatch latch1 = new CountDownLatch(1); pool .acquire(context, 0, TestUtils.onSuccess2(lease -> { @@ -977,7 +985,7 @@ public void testConnectionSelector() throws Exception { public void testDefaultSelector() throws Exception { ContextImpl context1 = (ContextImpl) vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 10 }, 10); + ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); CountDownLatch latch1 = new CountDownLatch(1); pool .acquire(context1, 0, TestUtils.onSuccess2(lease -> { @@ -1017,7 +1025,7 @@ public void testDefaultSelector() throws Exception { public void testDefaultContextProviderUnwrap() { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 10 }, 10); + ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); pool .acquire(context.duplicate(), 0, TestUtils.onSuccess2(lease -> { })); @@ -1030,7 +1038,7 @@ public void testDefaultContextProviderUnwrap() { public void testDefaultContextProviderReusesSameEventLoop() { ContextInternal context = vertx.createWorkerContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 10 }, 10); + ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); pool .acquire(context.duplicate(), 0, TestUtils.onSuccess2(lease -> { })); @@ -1048,7 +1056,7 @@ public void testPostTasksTrampoline() throws Exception { AtomicInteger seq = new AtomicInteger(); CountDownLatch latch = new CountDownLatch(1 + numAcquires); int[] count = new int[1]; - ConnectionPool pool = ConnectionPool.pool(new PoolConnector() { + ConnectionPool pool = pool(new PoolConnector() { int reentrancy = 0; @Override public Future> connect(ContextInternal context, Listener listener) { @@ -1100,7 +1108,7 @@ public void testConcurrentPostTasksTrampoline() throws Exception { ContextInternal ctx = vertx.createEventLoopContext(); List res = Collections.synchronizedList(new LinkedList<>()); CountDownLatch latch = new CountDownLatch(4); - ConnectionPool pool1 = ConnectionPool.pool(new PoolConnector<>() { + ConnectionPool pool1 = pool(new PoolConnector<>() { int count = 0; int reentrancy = 0; @Override @@ -1132,7 +1140,7 @@ public boolean isValid(Connection connection) { return true; } }, new int[]{1}, 2); - ConnectionPool pool2 = ConnectionPool.pool(new PoolConnector<>() { + ConnectionPool pool2 = pool(new PoolConnector<>() { int count = 0; int reentrancy = 0; @Override diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java new file mode 100644 index 00000000000..58a81adb14a --- /dev/null +++ b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ +package io.vertx.tests.pool; + +import io.vertx.core.internal.pool.ConnectionPool; +import io.vertx.core.internal.pool.PoolConnector; +import io.vertx.core.internal.pool.DefaultConnectionPool; + +public class DefaultConnectionPoolTest extends ConnectionPoolTest { + + @Override + protected ConnectionPool pool(PoolConnector connector, int[] maxSizes) { + return DefaultConnectionPool.pool(connector, maxSizes); + } + + @Override + protected ConnectionPool pool(PoolConnector connector, int[] maxSizes, int maxWaiters) { + return DefaultConnectionPool.pool(connector, maxSizes, maxWaiters); + } +} From 2388f005b4fd95273a0c0c1d127bd6489b673004 Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Thu, 26 Nov 2026 09:42:28 +0100 Subject: [PATCH 05/18] Fold the task list building into a TaskList Motivation: Building a task list juggles a head/tail pair of locals, repeating the append lines at every site. Changes: A TaskList builds the task list with an append method returning the first task, used wherever a task list is built. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../internal/pool/DefaultConnectionPool.java | 30 +++++++++++++++---- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java index 5e1a61c7836..04df825c8f5 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java @@ -566,21 +566,20 @@ public void run() { res.add(slot.connection); } } - Task head = new Task() { + TaskList tasks = new TaskList(); + tasks.append(new Task() { @Override public void run() { handler.succeed(res); } - }; - Task tail = head; + }); for (Slot slot : removed) { Task next = new Remove<>(slot).execute(pool); if (next != null) { - tail.next(next); - tail = next; + tasks.append(next); } } - return head; + return tasks.first(); } } @@ -960,4 +959,23 @@ public int size() { return size; } } + + private static class TaskList { + + private Task head; + private Task tail; + + void append(Task task) { + if (head == null) { + head = task; + } else { + tail.next(task); + } + tail = task; + } + + Task first() { + return head; + } + } } From e2aafa2c5c27bac3ae752b6774be0bad1ef96ba9 Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Wed, 25 Nov 2026 16:53:40 +0100 Subject: [PATCH 06/18] Test the capacity overshoot of concurrent acquisitions Motivation: Concurrent acquisitions bet on a connection kind, the actual kind is known on connect success only: when the back-end establishes heavier connections, the pool temporarily exceeds its maximum capacity. This expected outlier is accepted and was not pinned by the test suite. Changes: Add testCapacityOvershoot to the shared suite: five concurrent acquisitions of the first kind established as the heavier kind exceed the maximum capacity and are all served; nothing is created while the pool is over capacity, the next acquisition waits. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../vertx/tests/pool/ConnectionPoolTest.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java index d09d4a4ca8f..f432d17e7ae 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java @@ -613,6 +613,32 @@ public void testHeterogeneousSizes() throws Exception { Assert.assertEquals(1, pool.waiters()); } + @Test + public void testCapacityOvershoot() throws Exception { + // This tests an expected outlier of the capacity bound: concurrent acquisitions bet on a + // kind, the actual kind is known on connect success only + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = pool(mgr, new int[] { 5, 1 }); + ContextInternal ctx = vertx.createEventLoopContext(); + CountDownLatch latch = new CountDownLatch(5); + for (int i = 0;i < 5;i++) { + pool.acquire(ctx, 0, TestUtils.onSuccess2(lease -> latch.countDown())); + } + // The back-end establishes connections of the heavier kind: the pool temporarily exceeds + // its maximum capacity, this is accepted + for (int i = 0;i < 5;i++) { + mgr.assertRequest().connect(new Connection(), 1); + } + TestUtils.awaitLatch(latch); + Assert.assertEquals(5, pool.size()); + Assert.assertEquals(25, pool.capacity()); + // Nothing is created while the pool is over capacity: the next acquisition waits + pool.acquire(ctx, 0, TestUtils.onSuccess2(lease -> { + })); + Assert.assertEquals(1, pool.waiters()); + Assert.assertEquals(0, pool.requests()); + } + @Test public void testClose() throws Exception { ConnectionManager mgr = new ConnectionManager(); From f8ba4bd4e51644e69001c54ddbc64b981c9db731 Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Tue, 24 Nov 2026 16:51:18 +0100 Subject: [PATCH 07/18] Convert the actions to recordings driving a single progress method Motivation: Actions record state changes and a single progress method makes the decisions, instead of duplicating the logic across actions. Changes: The wait queue is the demand: connecting waiters stay in it, covered by the in-flight connects, and a connect no longer references its initiating waiter. Actions record their state change and delegate to progress(), made of flat sections: the connect failure policy (the default fails one pending acquisition per recorded failure), the satisfaction loop (selector grant, connection creation for uncovered demand, fallback grant), the admission of submitted acquisitions bounded by maxWaiters, the onEnqueue notifications and the connect result signalling. Cancel succeeds iff the acquisition is not settled, and settles it. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../internal/pool/DefaultConnectionPool.java | 543 +++++++++--------- .../vertx/tests/pool/ConnectionPoolTest.java | 18 + 2 files changed, 295 insertions(+), 266 deletions(-) diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java index 04df825c8f5..99a0c9ef0ef 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java @@ -113,8 +113,7 @@ static class Slot implements PoolConnector.Listener, PoolConnection { private final DefaultConnectionPool pool; private final ContextInternal context; - private final Promise result; - private PoolWaiter initiator; + private Promise result; private C connection; // The actual connection, might be null private int index; // The index in the pool slots array private int usage; // The number of times this connection is acquired @@ -187,10 +186,22 @@ public long concurrency() { private int size; // The number of non null slots private int capacity; // The pool capacity - // The waiters + // The submitted waiters, not yet acknowledged + private final Waiters submitted; + + // The waiters acknowledged in the wait queue private final Waiters waiters; + + // Scratch structures of the progress, allocated once and reused between runs: the executor + // guarantees a single progress at a time + private final TaskList tasks; + private final List> admitted; + private int requests; + // The recorded connect failure + private Throwable failureCause; + public static DefaultConnectionPool pool(PoolConnector connector, int[] maxSizes) { return new DefaultConnectionPool<>(connector, maxSizes); } @@ -260,7 +271,10 @@ public DefaultConnectionPool build() { this.selector = (BiFunction) SAME_EVENT_LOOP_SELECTOR; this.fallbackSelector = (BiFunction) FIRST_AVAILABLE_SELECTOR; this.contextProvider = EVENT_LOOP_CONTEXT_PROVIDER; + this.submitted = new Waiters<>(); this.waiters = new Waiters<>(); + this.tasks = new TaskList(); + this.admitted = new ArrayList<>(); } @Override @@ -279,18 +293,213 @@ private void execute(Executor.Action> action) { sync.submit(action); } + private void removeSlot(Slot slot) { + int w = slot.capacity; + slot.usage = 0; + slot.concurrency = 0; + slot.connection = null; + slot.capacity = 0; + if (size > 1) { + Slot tmp = slots[size - 1]; + tmp.index = slot.index; + slots[slot.index] = tmp; + slots[size - 1] = null; + } else { + slots[0] = null; + } + size--; + capacity -= w; + } + + private boolean isWaitersQueueFull() { + return maxWaiters != -1 && waiters.size() >= maxWaiters; + } + + private Task progress() { + progress(tasks); + Task head = tasks.first(); + tasks.clear(); + return head; + } + + private void progress(TaskList tasks) { + + // Connect failure policy: fail one pending acquisition per recorded failure, alternative + // policies (bounded retry, fail-fast, ...) plug in here. + // Under persistent failures this signals every waiter: each failure fails the head while the + // loop below connects for the next one, until the wait queue is empty. To reconsider if the + // pool gets time based eviction of waiters, guaranteeing the signalling instead + if (failureCause != null) { + Throwable cause = failureCause; + failureCause = null; + PoolWaiter waiter = waiters.poll(); + if (waiter != null) { + waiter.disposed = true; + Task task = new Task() { + @Override + public void run() { + waiter.handler.fail(cause); + } + }; + tasks.append(task); + } + } + + + // Satisfy the demand: peek from the wait queue, when it is exhausted peek from the submitted + // acquisitions, stop at the first demand that cannot be satisfied; the first requests waiters + // are covered by in-flight connects: they can be granted but no connection is created for them + int pos = 0; + PoolWaiter next = waiters.peek(); + while (true) { + boolean submission; + PoolWaiter waiter; + if (next != null) { + submission = false; + waiter = next; + next = waiters.next(next); + } else if ((waiter = submitted.poll()) != null) { + // Admit a submission in the wait queue, the bound is enforced only when it remains waiting: + // a submission served by a grant or a connect is exempted, like the existing pool + submission = true; + waiters.addLast(waiter); + admitted.add(waiter); + } else { + break; + } + Task task = null; + Slot slot1; + Slot slot3; + // 1. Try reuse a existing connection with the same context + if ((slot1 = (Slot) selector.apply(waiter, list)) != null) { + waiters.remove(waiter); + waiter.disposed = true; + slot1.usage++; + LeaseImpl lease = new LeaseImpl<>(slot1, waiter.handler); + task = new Task() { + @Override + public void run() { + lease.emit(); + } + }; + } else if (pos >= requests && capacity < maxCapacity) { + // 2. Try create connection, the waiter joins the covered prefix of the wait queue + capacity += waiter.capacity; + ContextInternal connectionContext = contextProvider.apply(waiter.context); + Slot slot2 = new Slot<>(this, connectionContext, size, waiter.capacity); + slots[size++] = slot2; + requests++; + pos++; + task = new Task() { + @Override + public void run() { + if (waiter.listener != null) { + waiter.listener.onConnect(waiter); + } + connect(slot2); + } + }; + } else if ((slot3 = (Slot) fallbackSelector.apply(waiter, list)) != null) { + // 3. Try use another context + waiters.remove(waiter); + waiter.disposed = true; + slot3.usage++; + LeaseImpl lease = new LeaseImpl<>(slot3, waiter.handler); + task = new Task() { + @Override + public void run() { + lease.emit(); + } + }; + } else if (pos < requests) { + // 4. Covered by an in-flight connect, wait for it + pos++; + } else if (submission) { + // 5. The submission remains waiting, reject it when the wait queue exceeds the bound + if (maxWaiters != -1 && waiters.size() > maxWaiters) { + waiters.remove(waiter); + task = new Task() { + @Override + public void run() { + Future> fut = waiter.context.failedFuture(new ConnectionPoolTooBusyException("Connection pool reached max wait queue size of " + maxWaiters)); + fut.onComplete(waiter.handler); + } + }; + } else { + pos++; + } + } else { + // 6. No satisfaction is possible anymore + break; + } + if (task != null) { + tasks.append(task); + } + } + + + // Move the remaining submissions to the wait queue, reject them when it is full + for (PoolWaiter extra = submitted.poll();extra != null;extra = submitted.poll()) { + if (!isWaitersQueueFull()) { + waiters.addLast(extra); + admitted.add(extra); + } else { + PoolWaiter rejected = extra; + Task task = new Task() { + @Override + public void run() { + Future> fut = rejected.context.failedFuture(new ConnectionPoolTooBusyException("Connection pool reached max wait queue size of " + maxWaiters)); + fut.onComplete(rejected.handler); + } + }; + tasks.append(task); + } + } + + + // Notify the admitted submissions still waiting + for (PoolWaiter waiter : admitted) { + if (waiter.next != null && waiter.listener != null) { + Task task = new Task() { + @Override + public void run() { + waiter.listener.onEnqueue(waiter); + } + }; + tasks.append(task); + } + } + admitted.clear(); + + + // Signal the connect results + for (int i = 0;i < size;i++) { + Slot slot = slots[i]; + if (slot.result != null && slot.connection != null) { + Promise result = slot.result; + C connection = slot.connection; + slot.result = null; + Task task = new Task() { + @Override + public void run() { + result.complete(connection); + } + }; + tasks.append(task); + } + } + } + public int size() { return size; } - public void connect(Slot slot, PoolWaiter waiter) { - slot.initiator = waiter; + private void connect(Slot slot) { connector.connect(slot.context, slot).onComplete(ar -> { - slot.initiator = null; if (ar.succeeded()) { - execute(new ConnectSuccess<>(slot, ar.result(), waiter)); + execute(new ConnectSuccess<>(slot, ar.result())); } else { - execute(new ConnectFailed<>(slot, ar.cause(), waiter)); + execute(new ConnectFailed<>(slot, ar.cause())); } }); } @@ -299,12 +508,10 @@ private static class ConnectSuccess implements Executor.Action slot; private final ConnectResult result; - private PoolWaiter waiter; - private ConnectSuccess(Slot slot, ConnectResult result, PoolWaiter waiter) { + private ConnectSuccess(Slot slot, ConnectResult result) { this.slot = slot; this.result = result; - this.waiter = waiter; } @Override @@ -320,69 +527,14 @@ public Task execute(DefaultConnectionPool pool) { pool.requests--; pool.capacity += (capacity - initialCapacity); if (pool.closed) { - if (waiter.disposed) { - waiter = null; - } else { - waiter.disposed = true; - } return new Task() { @Override public void run() { - if (waiter != null) { - Future> fut = slot.context.failedFuture("Pool closed"); - fut.onComplete(waiter.handler); - } - slot.result.complete(slot.connection); - } - }; - } else { - long acquisitions = slot.concurrency; - if (acquisitions == 0) { - if (!waiter.disposed) { - pool.waiters.addFirst(waiter); - } - return null; - } - LeaseImpl lease; - int c; - if (waiter.disposed) { - lease = null; - c = 0; - } else { - lease = new LeaseImpl<>(slot, waiter.handler); - c = 1; - waiter.disposed = true; - acquisitions--; - } - LeaseImpl[] leases; - int m = (int)Math.min(acquisitions, pool.waiters.size()); - if (m > 0) { - c += m; - leases = new LeaseImpl[m]; - for (int i = 0;i < m;i++) { - PoolWaiter w = pool.waiters.poll(); - w.disposed = true; - leases[i] = new LeaseImpl<>(slot, w.handler); - } - } else { - leases = null; - } - slot.usage = c; - return new Task() { - @Override - public void run() { - if (lease != null) { - lease.emit(); - } - if (leases != null) { - for (LeaseImpl lease : leases) { - lease.emit(); - } - } slot.result.complete(slot.connection); } }; } + return pool.progress(); } } @@ -390,44 +542,32 @@ private static class ConnectFailed implements Executor.Action removed; private final Throwable cause; - private PoolWaiter waiter; - public ConnectFailed(Slot removed, Throwable cause, PoolWaiter waiter) { + public ConnectFailed(Slot removed, Throwable cause) { this.removed = removed; this.cause = cause; - this.waiter = waiter; } public Task execute(DefaultConnectionPool pool) { pool.requests--; - if (waiter.disposed) { - waiter = null; - } else { - waiter.disposed = true; - } Task task = new Task() { @Override public void run() { - if (waiter != null) { - Throwable waiterFailure; - if (pool.closed) { - waiterFailure = POOL_CLOSED_EXCEPTION; - } else { - waiterFailure = cause; - } - waiter.handler.fail(waiterFailure); - } removed.result.fail(cause); } }; - if (!pool.closed) { - Task removeTask = new Remove<>(removed).execute(pool); - if (removeTask != null) { - removeTask.next(task); - task = removeTask; - } + if (pool.closed) { + return task; + } + pool.removeSlot(removed); + pool.failureCause = cause; + Task head = pool.progress(); + if (head == null) { + head = task; + } else { + head.last().next(task); } - return task; + return head; } } @@ -444,42 +584,8 @@ public Task execute(DefaultConnectionPool pool) { if (pool.closed || pool.slots[removed.index] != removed) { return null; } - int w = removed.capacity; - removed.usage = 0; - removed.concurrency = 0; - removed.connection = null; - removed.capacity = 0; - PoolWaiter waiter = pool.waiters.poll(); - if (waiter != null) { - ContextInternal connectionContext = pool.contextProvider.apply(waiter.context); - Slot slot = new Slot<>(pool, connectionContext, removed.index, waiter.capacity); - pool.capacity -= w; - pool.capacity += waiter.capacity; - pool.slots[removed.index] = slot; - pool.requests++; - return new Task() { - @Override - public void run() { - if (waiter.listener != null) { - waiter.listener.onConnect(waiter); - } - pool.connect(slot, waiter); - } - }; - } else if (pool.size > 1) { - Slot tmp = pool.slots[pool.size - 1]; - tmp.index = removed.index; - pool.slots[removed.index] = tmp; - pool.slots[pool.size - 1] = null; - pool.size--; - pool.capacity -= w; - return null; - } else { - pool.slots[0] = null; - pool.size--; - pool.capacity -= w; - return null; - } + pool.removeSlot(removed); + return pool.progress(); } } @@ -496,36 +602,10 @@ private static class SetConcurrency implements Executor.Action pool) { if (slot.connection != null) { - long diff = concurrency - slot.concurrency; - slot.concurrency += diff; - if (diff > 0) { - LeaseImpl[] extra; - int m = (int)Math.min(slot.concurrency - slot.usage, pool.waiters.size()); - if (m > 0) { - extra = new LeaseImpl[m]; - for (int i = 0;i < m;i++) { - PoolWaiter w = pool.waiters.poll(); - w.disposed = true; - extra[i] = new LeaseImpl<>(slot, w.handler); - } - slot.usage += m; - return new Task() { - @Override - public void run() { - for (LeaseImpl lease : extra) { - lease.emit(); - } - } - }; - } else { - return null; - } - } else { - return null; - } - } else { - return null; + slot.concurrency = concurrency; + return pool.progress(); } + return null; } } @@ -558,12 +638,11 @@ public void run() { }; } List res = new ArrayList<>(); - List> removed = new ArrayList<>(); for (int i = pool.size - 1;i >= 0;i--) { Slot slot = pool.slots[i]; if (slot.connection != null && slot.usage == 0 && predicate.test(slot.connection)) { - removed.add(slot); res.add(slot.connection); + pool.removeSlot(slot); } } TaskList tasks = new TaskList(); @@ -573,11 +652,9 @@ public void run() { handler.succeed(res); } }); - for (Slot slot : removed) { - Task next = new Remove<>(slot).execute(pool); - if (next != null) { - tasks.append(next); - } + Task next = pool.progress(); + if (next != null) { + tasks.append(next); } return tasks.first(); } @@ -605,73 +682,10 @@ public void run() { } }; } - - // 1. Try reuse a existing connection with the same context - Slot slot1 = (Slot) pool.selector.apply(this, pool.list); - if (slot1 != null) { - slot1.usage++; - LeaseImpl lease = new LeaseImpl<>(slot1, handler); - return new Task() { - @Override - public void run() { - lease.emit(); - } - }; - } - - // 2. Try create connection - if (pool.capacity < pool.maxCapacity) { - pool.capacity += capacity; - ContextInternal connectionContext = pool.contextProvider.apply(context); - Slot slot2 = new Slot<>(pool, connectionContext, pool.size, capacity); - pool.slots[pool.size++] = slot2; - pool.requests++; - return new Task() { - @Override - public void run() { - if (listener != null) { - listener.onConnect(Acquire.this); - } - pool.connect(slot2, Acquire.this); - } - }; - } - - // 3. Try use another context - Slot slot3 = (Slot) pool.fallbackSelector.apply(this, pool.list); - if (slot3 != null) { - slot3.usage++; - LeaseImpl lease = new LeaseImpl<>(slot3, handler); - return new Task() { - @Override - public void run() { - lease.emit(); - } - }; - } - - // 4. Fall in waiters list - if (pool.maxWaiters == -1 || (pool.waiters.size() + pool.requests) < pool.maxWaiters) { - pool.waiters.addLast(this); - if (listener != null) { - return new Task() { - @Override - public void run() { - listener.onEnqueue(Acquire.this); - } - }; - } else { - return null; - } - } else { - return new Task() { - @Override - public void run() { - Future> fut = context.failedFuture(new ConnectionPoolTooBusyException("Connection pool reached max wait queue size of " + pool.maxWaiters)); - fut.onComplete(handler); - } - }; - } + pool.submitted.addLast(this); + Task head = pool.progress(); + assert pool.submitted.size() == 0; + return head; } } @@ -711,15 +725,8 @@ public void run() { } }; } - if (pool.waiters.remove(waiter)) { - cancelled = true; - waiter.disposed = true; - } else if (!waiter.disposed) { - waiter.disposed = true; - cancelled = true; - } else { - cancelled = false; - } + cancelled = pool.waiters.remove(waiter) || !waiter.disposed; + waiter.disposed = true; return this; } @@ -769,19 +776,8 @@ public Recycle(Slot slot) { @Override public Task execute(DefaultConnectionPool pool) { if (!pool.closed && slot.connection != null) { - PoolWaiter waiter; - if (slot.usage <= slot.concurrency && (waiter = pool.waiters.poll()) != null) { - waiter.disposed = true; - LeaseImpl lease = new LeaseImpl<>(slot, waiter.handler); - return new Task() { - @Override - public void run() { - lease.emit(); - } - }; - } else { - slot.usage--; - } + slot.usage--; + return pool.progress(); } return null; } @@ -796,7 +792,7 @@ private void recycle(LeaseImpl lease) { } public int waiters() { - return waiters.size(); + return Math.max(0, waiters.size() - requests); } public int capacity() { @@ -832,14 +828,12 @@ public void run() { for (int i = 0;i < pool.size;i++) { Slot slot = pool.slots[i]; pool.slots[i] = null; - PoolWaiter waiter = slot.initiator; - if (waiter != null) { - waiters.add(slot.initiator); - slot.initiator.disposed = true; - slot.initiator = null; - } pool.capacity -= slot.capacity; - list.add(slot.result.future()); + if (slot.result != null) { + list.add(slot.result.future()); + } else { + list.add(slot.context.succeededFuture(slot.connection)); + } } pool.size = 0; return new Task() { @@ -869,6 +863,18 @@ public Waiters() { head.next = head.prev = head; } + PoolWaiter peek() { + return head.next == head ? null : head.next; + } + + PoolWaiter next(PoolWaiter node) { + return node.next == head ? null : node.next; + } + + PoolWaiter peekLast() { + return head.prev == head ? null : head.prev; + } + PoolWaiter poll() { if (head.next == head) { return null; @@ -879,10 +885,9 @@ PoolWaiter poll() { } void addLast(PoolWaiter node) { - if (node.queued) { + if (node.next != null) { throw new IllegalStateException(); } - node.queued = true; node.prev = head.prev; node.next = head; head.prev.next = node; @@ -891,10 +896,9 @@ void addLast(PoolWaiter node) { } void addFirst(PoolWaiter node) { - if (node.queued) { + if (node.next != null) { throw new IllegalStateException(); } - node.queued = true; node.prev = head; node.next = head.next; head.next.prev = node; @@ -903,13 +907,12 @@ void addFirst(PoolWaiter node) { } boolean remove(PoolWaiter node) { - if (!node.queued) { + if (node.next == null) { return false; } node.next.prev = node.prev; node.prev.next = node.next; node.next = node.prev = null; - node.queued = false; size--; return true; } @@ -917,6 +920,9 @@ boolean remove(PoolWaiter node) { List> clear() { List> lst = new ArrayList<>(size); this.forEach(lst::add); + for (PoolWaiter node : lst) { + node.next = node.prev = null; + } size = 0; head.next = head.prev = head; return lst; @@ -977,5 +983,10 @@ void append(Task task) { Task first() { return head; } + + void clear() { + head = null; + tail = null; + } } } diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java index f432d17e7ae..56d259c3038 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java @@ -1247,6 +1247,24 @@ public void fail(Throwable cause) { } } + @Test + public void testMaxWaitersDoesNotBoundConnectionCreation() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 0); + Connection expected = new Connection(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + Assert.assertSame(expected, lease.get()); + // The pool is full and waiting is not permitted + pool.acquire(context, 0, TestUtils.onFailure2(err -> { + Assert.assertTrue(err instanceof ConnectionPoolTooBusyException); + testComplete(); + })); + })); + mgr.assertRequest().connect(expected, 0); + await(); + } + class ConnectionManager implements PoolConnector { private final Queue requests = new ArrayBlockingQueue<>(100); From c00aefaa0fb6ab4963353533f15ac05c0e593b96 Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Tue, 24 Nov 2026 17:05:56 +0100 Subject: [PATCH 08/18] Run the pool stress test against DefaultConnectionPool StressTest builds its pool through an overridable method and DefaultConnectionPoolStressTest runs the same test against DefaultConnectionPool. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../pool/DefaultConnectionPoolStressTest.java | 23 +++++++++++++++++++ .../java/io/vertx/tests/pool/StressTest.java | 6 ++++- 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolStressTest.java diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolStressTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolStressTest.java new file mode 100644 index 00000000000..b5ce8367917 --- /dev/null +++ b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolStressTest.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ +package io.vertx.tests.pool; + +import io.vertx.core.internal.pool.ConnectionPool; +import io.vertx.core.internal.pool.DefaultConnectionPool; +import io.vertx.core.internal.pool.PoolConnector; + +public class DefaultConnectionPoolStressTest extends StressTest { + + @Override + protected ConnectionPool pool(PoolConnector connector, int[] maxSizes, int maxWaiters) { + return DefaultConnectionPool.pool(connector, maxSizes, maxWaiters); + } +} diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/StressTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/StressTest.java index 930adde2ee4..1997775a560 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/StressTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/StressTest.java @@ -28,12 +28,16 @@ */ public class StressTest extends VertxTestBase { + protected ConnectionPool pool(PoolConnector connector, int[] maxSizes, int maxWaiters) { + return ConnectionPool.pool(connector, maxSizes, maxWaiters); + } + class FakeConnectionPool implements PoolConnector { private ConnectionPool pool; FakeConnectionPool(int queueMaxSize, int poolMaxSize) { - this.pool = ConnectionPool.pool(this, new int[]{ poolMaxSize }, queueMaxSize); + this.pool = pool(this, new int[]{ poolMaxSize }, queueMaxSize); } void getConnection(FakeWaiter waiter) { From 98adcef61f9e420b778ffbf702630869b64b772c Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Wed, 25 Nov 2026 08:58:58 +0100 Subject: [PATCH 09/18] Add a refresh method to the connection pool contract The pool is refreshed periodically to check and perform the maintenance tasks to do: expired connection eviction, and later connect retry backoff or minimum connections maintenance. Depending on the granularity of the period, deadlines might be passed, which is acceptable. The implementations are empty for now. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../java/io/vertx/core/internal/pool/ConnectionPool.java | 7 +++++++ .../io/vertx/core/internal/pool/DefaultConnectionPool.java | 4 ++++ .../io/vertx/core/internal/pool/SimpleConnectionPool.java | 4 ++++ 3 files changed, 15 insertions(+) diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/ConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/ConnectionPool.java index 7a7763caf6a..85af646e15e 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/ConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/ConnectionPool.java @@ -70,6 +70,13 @@ static ConnectionPool pool(PoolConnector connector, int[] maxSizes, in */ ConnectionPool contextProvider(Function contextProvider); + /** + * Refresh the pool: check and perform the maintenance tasks to do, this method + * should be called periodically. Depending on the granularity of the period, + * deadlines might be passed, which is acceptable. + */ + void refresh(); + /** * Acquire a connection from the pool. * diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java index 99a0c9ef0ef..64560d5c518 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java @@ -689,6 +689,10 @@ public void run() { } } + @Override + public void refresh() { + } + @Override public void acquire(ContextInternal context, int kind, Completable> handler) { execute(new Acquire<>(context, PoolWaiter.NULL_LISTENER, capacityFactors[kind], handler)); diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/SimpleConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/SimpleConnectionPool.java index 782a3dbf891..37ccc83d2b7 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/SimpleConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/SimpleConnectionPool.java @@ -638,6 +638,10 @@ public void run() { } } + @Override + public void refresh() { + } + @Override public void acquire(ContextInternal context, int kind, Completable> handler) { execute(new Acquire<>(context, PoolWaiter.NULL_LISTENER, capacityFactors[kind], handler)); From d682555866cee0d9f9fb817f92fec45b0800d53a Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Wed, 25 Nov 2026 09:11:11 +0100 Subject: [PATCH 10/18] Combiner executor try submission and final action Motivation: Periodic pool maintenance should not run in the middle of other changes being applied, and detections like the connections to close should happen at the very end of an execution round, on the settled state. Changes: Executor.trySubmit executes an action only when the ownership of the execution can be acquired (acquire first then enqueue), otherwise does nothing - fine for idempotent periodic maintenance since any in-flight execution performs the same work. CombinerExecutor accepts an optional Supplier> finalAction, evaluated at the end of each execution round with exclusive access, after the submitted actions, its tasks running after the other tasks; the supplier decides (can return null). A refresh then reduces to try submitting a no-op action. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../core/internal/pool/CombinerExecutor.java | 38 +++++++++ .../io/vertx/core/internal/pool/Executor.java | 9 +++ .../core/internal/pool/SemaphoreExecutor.java | 13 ++++ .../vertx/tests/pool/SynchronizationTest.java | 78 +++++++++++++++++++ 4 files changed, 138 insertions(+) diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/CombinerExecutor.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/CombinerExecutor.java index 5a4a3bad50f..8f8542b5daf 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/CombinerExecutor.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/CombinerExecutor.java @@ -17,6 +17,7 @@ import java.util.Map; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; /** * Lock free executor. @@ -30,6 +31,7 @@ public class CombinerExecutor implements Executor { private final Queue> q = PlatformDependent.newMpscQueue(); private final AtomicInteger s = new AtomicInteger(); private final S state; + private final Supplier> finalAction; protected static final class InProgressTail { @@ -46,7 +48,12 @@ public InProgressTail(CombinerExecutor combiner, Task task) { private static final FastThreadLocal> current = new FastThreadLocal<>(); public CombinerExecutor(S state) { + this(state, null); + } + + public CombinerExecutor(S state, Supplier> finalAction) { this.state = state; + this.finalAction = finalAction; } @Override @@ -55,6 +62,20 @@ public void submit(Action action) { if (s.get() != 0 || !s.compareAndSet(0, 1)) { return; } + drain(); + } + + @Override + public boolean trySubmit(Action action) { + if (s.get() != 0 || !s.compareAndSet(0, 1)) { + return false; + } + q.add(action); + drain(); + return true; + } + + private void drain() { Task head = null; Task tail = null; do { @@ -77,6 +98,23 @@ public void submit(Action action) { } } } + if (finalAction != null) { + Action a = finalAction.get(); + if (a != null) { + final Task task = a.execute(state); + if (task != null) { + Task last = task.last(); + if (head == null) { + assert tail == null; + tail = last; + head = task; + } else { + tail.next(task); + tail = last; + } + } + } + } } finally { s.set(0); } diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/Executor.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/Executor.java index 5f74371e3ec..27ef0fe087d 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/Executor.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/Executor.java @@ -38,4 +38,13 @@ interface Action { */ void submit(Action action); + /** + * Submit an action to execute only when the ownership of the execution can be acquired, + * otherwise do nothing. + * + * @param action the action + * @return whether the action was executed + */ + boolean trySubmit(Action action); + } diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/SemaphoreExecutor.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/SemaphoreExecutor.java index 5fd22b12380..ca766c39da9 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/SemaphoreExecutor.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/SemaphoreExecutor.java @@ -25,6 +25,19 @@ public SemaphoreExecutor(S state) { @Override public void submit(Action action) { lock.lock(); + execute(action); + } + + @Override + public boolean trySubmit(Action action) { + if (!lock.tryLock()) { + return false; + } + execute(action); + return true; + } + + private void execute(Action action) { Task post = null; try { post = action.execute(state); diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/SynchronizationTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/SynchronizationTest.java index 7a02dc42977..28b0df588ea 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/SynchronizationTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/SynchronizationTest.java @@ -234,4 +234,82 @@ public void run() { } assertEquals(expected, io.netty.util.internal.InternalThreadLocalMap.lastVariableIndex()); } + + @Test + public void testTrySubmit() { + AtomicInteger state = new AtomicInteger(); + Executor sync = new CombinerExecutor<>(state); + boolean executed = sync.trySubmit(s -> { + s.incrementAndGet(); + return null; + }); + assertTrue(executed); + assertEquals(1, state.get()); + } + + @Test + public void testTrySubmitWhileExecuting() { + AtomicInteger state = new AtomicInteger(); + Executor sync = new CombinerExecutor<>(state); + AtomicBoolean executed = new AtomicBoolean(true); + sync.submit(s1 -> { + executed.set(sync.trySubmit(s2 -> { + s2.incrementAndGet(); + return null; + })); + return null; + }); + assertFalse(executed.get()); + assertEquals(0, state.get()); + } + + @Test + public void testFinalAction() { + List log = new LinkedList<>(); + AtomicInteger state = new AtomicInteger(); + CombinerExecutor sync = new CombinerExecutor<>(state, () -> s -> { + log.add("last:" + s.get()); + return new Task() { + @Override + public void run() { + log.add("last-task"); + } + }; + }); + sync.submit(s1 -> { + sync.submit(s2 -> { + s2.set(2); + log.add("action2"); + return null; + }); + s1.set(1); + log.add("action1"); + return new Task() { + @Override + public void run() { + log.add("task1"); + } + }; + }); + // The final action executes once per round, after the submitted actions, seeing the settled state, + // its tasks run after the other tasks + assertEquals(Arrays.asList("action1", "action2", "last:2", "task1", "last-task"), log); + } + + @Test + public void testTrySubmitFinalAction() { + List log = new LinkedList<>(); + AtomicInteger state = new AtomicInteger(); + CombinerExecutor sync = new CombinerExecutor<>(state, () -> s -> { + log.add("last:" + s.get()); + return null; + }); + boolean executed = sync.trySubmit(s -> { + s.set(1); + log.add("action"); + return null; + }); + assertTrue(executed); + assertEquals(Arrays.asList("action", "last:1"), log); + } } From 5c8432566952fe1cd37923dcc0ba2e3f863f8847 Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Wed, 25 Nov 2026 09:29:47 +0100 Subject: [PATCH 11/18] Evict the stale connections at the beginning of the execution round Motivation: A connection that is not valid is expired: the notion of expiration belongs to the connector. Evicting the stale connections before any demand is served establishes the invariant that within an execution round, every action operates on valid connections - the first progress of the round checks, the others assume. Changes: PoolConnector gains a close method to close the connections evicted by the pool. The first progress of an execution round evicts the stale connections and closes them, gated by a first flag re-armed by the final action at the end of the round. refresh() try submits a progress nudge: when the combiner is busy, the in-flight round already performed the eviction. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../internal/pool/DefaultConnectionPool.java | 50 ++++++++++++++++++- .../core/internal/pool/PoolConnector.java | 13 ++++- .../vertx/tests/pool/ConnectionPoolTest.java | 9 +++- .../tests/pool/DefaultConnectionPoolTest.java | 50 +++++++++++++++++++ 4 files changed, 118 insertions(+), 4 deletions(-) diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java index 64560d5c518..680e06acf9f 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java @@ -202,6 +202,9 @@ public long concurrency() { // The recorded connect failure private Throwable failureCause; + // Whether the next progress is the first of the execution round + private boolean first = true; + public static DefaultConnectionPool pool(PoolConnector connector, int[] maxSizes) { return new DefaultConnectionPool<>(connector, maxSizes); } @@ -267,7 +270,7 @@ public DefaultConnectionPool build() { this.maxWaiters = maxWaiters; this.capacity = 0; this.maxCapacity = maxCapacity; - this.sync = new CombinerExecutor<>(this); + this.sync = new CombinerExecutor<>(this, this::finalAction); this.selector = (BiFunction) SAME_EVENT_LOOP_SELECTOR; this.fallbackSelector = (BiFunction) FIRST_AVAILABLE_SELECTOR; this.contextProvider = EVENT_LOOP_CONTEXT_PROVIDER; @@ -293,6 +296,19 @@ private void execute(Executor.Action> action) { sync.submit(action); } + private Executor.Action> finalAction() { + return first ? null : new Cleanup<>(); + } + + private static class Cleanup implements Executor.Action> { + + @Override + public Task execute(DefaultConnectionPool pool) { + pool.first = true; + return null; + } + } + private void removeSlot(Slot slot) { int w = slot.capacity; slot.usage = 0; @@ -324,6 +340,26 @@ private Task progress() { private void progress(TaskList tasks) { + // On the first progress of the execution round, evict the stale connections before any + // demand is served: a connection that is not valid is expired + if (first) { + first = false; + for (int i = size - 1;i >= 0;i--) { + Slot slot = slots[i]; + if (slot.connection != null && slot.usage == 0 && !connector.isValid(slot.connection)) { + C connection = slot.connection; + removeSlot(slot); + Task task = new Task() { + @Override + public void run() { + connector.close(connection); + } + }; + tasks.append(task); + } + } + } + // Connect failure policy: fail one pending acquisition per recorded failure, alternative // policies (bounded retry, fail-fast, ...) plug in here. // Under persistent failures this signals every waiter: each failure fails the head while the @@ -691,6 +727,18 @@ public void run() { @Override public void refresh() { + sync.trySubmit(new Refresh<>()); + } + + private static class Refresh implements Executor.Action> { + + @Override + public Task execute(DefaultConnectionPool pool) { + if (pool.closed) { + return null; + } + return pool.progress(); + } } @Override diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolConnector.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolConnector.java index 04c31cf7204..6bfab1ca2dc 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolConnector.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolConnector.java @@ -32,14 +32,23 @@ public interface PoolConnector { /** * Checks whether the connection is still valid. * - *

The pool calls this method when it checks the validity of a connection. Any connection - * will be evicted from the pool. + *

A connection that is not valid is expired: the pool evicts it when it cleans up and + * closes it with {@link #close}. The notion of expiration belongs to the connector, e.g. a + * maximum lifetime or a broken connection. * * @param connection the connection to check * @return whether the connection is valid or not */ boolean isValid(C connection); + /** + * Close a connection evicted by the pool. + * + * @param connection the connection to close + */ + default void close(C connection) { + } + /** * The contract by which the back-end can signal the pool of connection events. * diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java index 56d259c3038..6c205aaccc2 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java @@ -1206,6 +1206,8 @@ public boolean isValid(Connection connection) { } static class Connection { + boolean valid = true; + boolean closed; public Connection() { } } @@ -1278,7 +1280,12 @@ public Future> connect(ContextInternal context, Listen @Override public boolean isValid(Connection connection) { - return true; + return connection.valid; + } + + @Override + public void close(Connection connection) { + connection.closed = true; } ConnectionRequest assertRequest() { diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java index 58a81adb14a..f25d96c7f57 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java @@ -10,12 +10,62 @@ */ package io.vertx.tests.pool; +import io.vertx.core.internal.ContextInternal; import io.vertx.core.internal.pool.ConnectionPool; import io.vertx.core.internal.pool.PoolConnector; import io.vertx.core.internal.pool.DefaultConnectionPool; +import io.vertx.test.core.TestUtils; +import org.junit.Assert; +import org.junit.Test; + +import java.util.concurrent.CountDownLatch; public class DefaultConnectionPoolTest extends ConnectionPoolTest { + @Test + public void testStaleConnectionEviction() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = pool(mgr, new int[] { 2 }); + Connection conn1 = new Connection(); + Connection conn2 = new Connection(); + CountDownLatch latch = new CountDownLatch(2); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + lease.recycle(); + latch.countDown(); + })); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + lease.recycle(); + latch.countDown(); + })); + mgr.assertRequest().connect(conn1, 0); + mgr.assertRequest().connect(conn2, 0); + TestUtils.awaitLatch(latch); + // A refresh does not evict valid connections + pool.refresh(); + Assert.assertEquals(2, pool.size()); + Assert.assertFalse(conn1.closed); + Assert.assertFalse(conn2.closed); + // A refresh evicts stale connections + conn1.valid = false; + pool.refresh(); + assertWaitUntil(() -> pool.size() == 1); + Assert.assertTrue(conn1.closed); + Assert.assertFalse(conn2.closed); + Assert.assertEquals(1, pool.capacity()); + // Borrowing evicts stale connections before serving: the acquisition gets a fresh connection + conn2.valid = false; + Connection conn3 = new Connection(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + Assert.assertSame(conn3, lease.get()); + Assert.assertTrue(conn2.closed); + testComplete(); + })); + mgr.assertRequest().connect(conn3, 0); + await(); + } + + @Override protected ConnectionPool pool(PoolConnector connector, int[] maxSizes) { return DefaultConnectionPool.pool(connector, maxSizes); From 75d6791a862d479edfc7d6784e6a5480ed146a42 Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Wed, 25 Nov 2026 09:49:38 +0100 Subject: [PATCH 12/18] Acquisition timeout Motivation: The connection acquisition timeout is implemented by the pool user with a timer and a cancellation. The pool can check the deadlines itself at the beginning of each execution round, like the stale connections. Changes: acquire overloads take a timeout, recorded as a nano time deadline on the waiter; the default implementations ignore it. At the beginning of an execution round, the pool removes the timed out waiters from the wait queue and signals the new PoolWaiter.Listener#onTimeout, nothing else: handling the timed out acquisition is up to the pool user. The timeout is checked when the pool executes, deadlines might be passed. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../core/internal/pool/ConnectionPool.java | 18 ++++++ .../internal/pool/DefaultConnectionPool.java | 40 +++++++++++-- .../vertx/core/internal/pool/PoolWaiter.java | 9 +++ .../tests/pool/DefaultConnectionPoolTest.java | 60 +++++++++++++++++++ 4 files changed, 122 insertions(+), 5 deletions(-) diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/ConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/ConnectionPool.java index 85af646e15e..540d254d2d4 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/ConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/ConnectionPool.java @@ -15,6 +15,7 @@ import io.vertx.core.internal.ContextInternal; import io.vertx.core.internal.VertxInternal; +import java.time.Duration; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; @@ -94,6 +95,23 @@ static ConnectionPool pool(PoolConnector connector, int[] maxSizes, in */ void acquire(ContextInternal context, PoolWaiter.Listener listener, int kind, Completable> handler); + /** + * Like {@link #acquire(ContextInternal, int, Completable)} with a timeout: when the acquisition + * remains pending after the timeout, the pool removes the waiter from the wait queue and signals + * {@link PoolWaiter.Listener#onTimeout}, nothing else. The timeout is checked when the pool + * executes, deadlines might be passed. The default implementation ignores the timeout. + */ + default void acquire(ContextInternal context, int kind, Duration timeout, Completable> handler) { + acquire(context, kind, handler); + } + + /** + * Like {@link #acquire(ContextInternal, PoolWaiter.Listener, int, Completable)} with a timeout. + */ + default void acquire(ContextInternal context, PoolWaiter.Listener listener, int kind, Duration timeout, Completable> handler) { + acquire(context, listener, kind, handler); + } + /** * Cancel a waiter. * diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java index 680e06acf9f..6a8edf9d8b1 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java @@ -14,6 +14,7 @@ import io.vertx.core.http.ConnectionPoolTooBusyException; import io.vertx.core.internal.ContextInternal; +import java.time.Duration; import java.util.AbstractList; import java.util.ArrayList; import java.util.Iterator; @@ -340,10 +341,26 @@ private Task progress() { private void progress(TaskList tasks) { - // On the first progress of the execution round, evict the stale connections before any - // demand is served: a connection that is not valid is expired + // On the first progress of the execution round, evict the timed out waiters and the stale + // connections before any demand is served: a connection that is not valid is expired if (first) { first = false; + long now = System.nanoTime(); + PoolWaiter current = waiters.peek(); + while (current != null) { + PoolWaiter waiter = current; + current = waiters.next(current); + if (waiter.deadlineNanos != 0 && now - waiter.deadlineNanos >= 0) { + waiters.remove(waiter); + Task task = new Task() { + @Override + public void run() { + waiter.listener.onTimeout(waiter); + } + }; + tasks.append(task); + } + } for (int i = size - 1;i >= 0;i--) { Slot slot = slots[i]; if (slot.connection != null && slot.usage == 0 && !connector.isValid(slot.connection)) { @@ -703,8 +720,11 @@ public void evict(Predicate predicate, Completable> handler) { private static class Acquire extends PoolWaiter implements Executor.Action> { - public Acquire(ContextInternal context, PoolWaiter.Listener listener, int capacity, Completable> handler) { + public Acquire(ContextInternal context, PoolWaiter.Listener listener, int capacity, Duration timeout, Completable> handler) { super(listener, context, capacity, handler); + if (timeout != null) { + deadlineNanos = System.nanoTime() + timeout.toNanos(); + } } @Override @@ -743,12 +763,22 @@ public Task execute(DefaultConnectionPool pool) { @Override public void acquire(ContextInternal context, int kind, Completable> handler) { - execute(new Acquire<>(context, PoolWaiter.NULL_LISTENER, capacityFactors[kind], handler)); + acquire(context, PoolWaiter.NULL_LISTENER, kind, null, handler); } @Override public void acquire(ContextInternal context, PoolWaiter.Listener listener, int kind, Completable> handler) { - execute(new Acquire<>(context, listener, capacityFactors[kind], handler)); + acquire(context, listener, kind, null, handler); + } + + @Override + public void acquire(ContextInternal context, int kind, Duration timeout, Completable> handler) { + acquire(context, PoolWaiter.NULL_LISTENER, kind, timeout, handler); + } + + @Override + public void acquire(ContextInternal context, PoolWaiter.Listener listener, int kind, Duration timeout, Completable> handler) { + execute(new Acquire<>(context, listener, capacityFactors[kind], timeout, handler)); } @Override diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolWaiter.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolWaiter.java index 5c834e64273..b2c363deb09 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolWaiter.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolWaiter.java @@ -41,6 +41,14 @@ default void onEnqueue(PoolWaiter waiter) { */ default void onConnect(PoolWaiter waiter) { } + + /** + * The waiter timed out: the pool removed it from the wait queue, nothing else. + * + * @param waiter the waiter + */ + default void onTimeout(PoolWaiter waiter) { + } } final PoolWaiter.Listener listener; @@ -51,6 +59,7 @@ default void onConnect(PoolWaiter waiter) { PoolWaiter next; boolean disposed; boolean queued; + long deadlineNanos; PoolWaiter(PoolWaiter.Listener listener, ContextInternal context, final int capacity, Completable> handler) { this.listener = listener; diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java index f25d96c7f57..cbfd844a61c 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java @@ -13,12 +13,15 @@ import io.vertx.core.internal.ContextInternal; import io.vertx.core.internal.pool.ConnectionPool; import io.vertx.core.internal.pool.PoolConnector; +import io.vertx.core.internal.pool.PoolWaiter; import io.vertx.core.internal.pool.DefaultConnectionPool; import io.vertx.test.core.TestUtils; import org.junit.Assert; import org.junit.Test; +import java.time.Duration; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; public class DefaultConnectionPoolTest extends ConnectionPoolTest { @@ -65,6 +68,63 @@ public void testStaleConnectionEviction() throws Exception { await(); } + @Test + public void testAcquireTimeout() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = pool(mgr, new int[] { 1 }); + Connection conn1 = new Connection(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + // The connection is held, the next acquisition waits + })); + mgr.assertRequest().connect(conn1, 0); + AtomicBoolean timedOut = new AtomicBoolean(); + pool.acquire(context, new PoolWaiter.Listener<>() { + @Override + public void onTimeout(PoolWaiter waiter) { + timedOut.set(true); + } + }, 0, Duration.ofMillis(20), (res, err) -> Assert.fail()); + assertWaitUntil(() -> pool.waiters() == 1); + assertWaitUntil(() -> { + pool.refresh(); + return timedOut.get(); + }); + Assert.assertEquals(0, pool.waiters()); + } + + + @Test + public void testConnectFailureRetainsWaiterTimeout() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = pool(mgr, new int[] { 1 }); + // A first acquisition connects + AtomicBoolean failed = new AtomicBoolean(); + pool.acquire(context, 0, (res, err) -> { + if (err != null) { + failed.set(true); + } + }); + ConnectionRequest request = mgr.assertRequest(); + // A second acquisition waits with a deadline, a third one waits + AtomicBoolean timedOut = new AtomicBoolean(); + pool.acquire(context, new PoolWaiter.Listener<>() { + @Override + public void onTimeout(PoolWaiter waiter) { + timedOut.set(true); + } + }, 0, Duration.ofMillis(10), (res, err) -> { + }); + pool.acquire(context, 0, (res, err) -> { + }); + Thread.sleep(20); + // The connect failure opens the round: the timed out waiter eviction and the connect failure + // policy are both signalled + request.fail(new Exception("failure")); + assertWaitUntil(failed::get); + Assert.assertTrue(timedOut.get()); + } @Override protected ConnectionPool pool(PoolConnector connector, int[] maxSizes) { From a68e40298dd813ca8336cca9ac6e667f3e9049be Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Wed, 25 Nov 2026 14:33:04 +0100 Subject: [PATCH 13/18] Connect retry delay Motivation: After a connect failure, the pool immediately attempts to reconnect for the remaining waiters, hammering a failed back-end. A reconnection strategy is the single gatekeeper for connect attempts; the simplest one suspends them for a delay. Changes: A DefaultConnectionPool builder configures an optional connect retry delay, kept final. Each execution round reasons against a single timestamp captured by its first progress, assuming tasks execute quickly. A connect failure suspends connection creation until the deadline and captures the number of connect successes since the pool creation; the first progress of a round lifts the suspension when the deadline has passed or when that number has increased, the evidence a connect succeeded since the suspension. While suspended, waiters covered by in-flight connects are still granted connections. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../internal/pool/DefaultConnectionPool.java | 47 ++++++++++--- .../vertx/tests/pool/ConnectionPoolTest.java | 8 +++ .../tests/pool/DefaultConnectionPoolTest.java | 69 +++++++++++++++++++ 3 files changed, 116 insertions(+), 8 deletions(-) diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java index 6a8edf9d8b1..4863271f3d6 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java @@ -203,6 +203,19 @@ public long concurrency() { // The recorded connect failure private Throwable failureCause; + // The number of connect successes since the pool creation + private long connectCount; + + // The reconnection strategy: no connect attempt before the suspension deadline, cleared at the + // round boundary when it expired or when a connect succeeded since it was armed + private final long retryDelayNanos; + private long suspendedUntilNanos; + private long suspendedConnectCount; + + // The time of the execution round, captured by its first progress: the round reasons + // against a single timestamp, assuming tasks execute quickly + private long roundNanos; + // Whether the next progress is the first of the execution round private boolean first = true; @@ -211,7 +224,7 @@ public static DefaultConnectionPool pool(PoolConnector connector, int[ } public static DefaultConnectionPool pool(PoolConnector connector, int[] maxSizes, int maxWaiters) { - return new DefaultConnectionPool<>(connector, maxSizes, maxWaiters); + return new DefaultConnectionPool<>(connector, maxSizes, maxWaiters, null); } public static Builder builder(PoolConnector connector) { @@ -223,6 +236,7 @@ public static class Builder { private final PoolConnector connector; private int[] maxSizes; private int maxWaiters = -1; + private Duration connectRetryDelay; Builder(PoolConnector connector) { this.connector = Objects.requireNonNull(connector); @@ -238,16 +252,21 @@ public Builder withMaxWaiters(int maxWaiters) { return this; } + public Builder withConnectRetryDelay(Duration connectRetryDelay) { + this.connectRetryDelay = connectRetryDelay; + return this; + } + public DefaultConnectionPool build() { - return new DefaultConnectionPool<>(connector, Objects.requireNonNull(maxSizes), maxWaiters); + return new DefaultConnectionPool<>(connector, Objects.requireNonNull(maxSizes), maxWaiters, connectRetryDelay); } } DefaultConnectionPool(PoolConnector connector, int[] maxSizes) { - this(connector, maxSizes, -1); + this(connector, maxSizes, -1, null); } - DefaultConnectionPool(PoolConnector connector, int[] maxSizes, int maxWaiters) { + DefaultConnectionPool(PoolConnector connector, int[] maxSizes, int maxWaiters, Duration connectRetryDelay) { int[] capacities = new int[maxSizes.length]; int maxCapacity = 1; @@ -279,6 +298,7 @@ public DefaultConnectionPool build() { this.waiters = new Waiters<>(); this.tasks = new TaskList(); this.admitted = new ArrayList<>(); + this.retryDelayNanos = connectRetryDelay == null ? 0L : connectRetryDelay.toNanos(); } @Override @@ -345,12 +365,16 @@ private void progress(TaskList tasks) { // connections before any demand is served: a connection that is not valid is expired if (first) { first = false; - long now = System.nanoTime(); + roundNanos = System.nanoTime(); + if (suspendedUntilNanos != 0 && (roundNanos - suspendedUntilNanos >= 0 || connectCount > suspendedConnectCount)) { + // The suspension of the reconnection strategy is over or a connect succeeded since it was armed + suspendedUntilNanos = 0; + } PoolWaiter current = waiters.peek(); while (current != null) { PoolWaiter waiter = current; current = waiters.next(current); - if (waiter.deadlineNanos != 0 && now - waiter.deadlineNanos >= 0) { + if (waiter.deadlineNanos != 0 && roundNanos - waiter.deadlineNanos >= 0) { waiters.remove(waiter); Task task = new Task() { @Override @@ -385,6 +409,10 @@ public void run() { if (failureCause != null) { Throwable cause = failureCause; failureCause = null; + if (retryDelayNanos > 0) { + suspendedUntilNanos = roundNanos + retryDelayNanos; + suspendedConnectCount = connectCount; + } PoolWaiter waiter = waiters.poll(); if (waiter != null) { waiter.disposed = true; @@ -401,7 +429,9 @@ public void run() { // Satisfy the demand: peek from the wait queue, when it is exhausted peek from the submitted // acquisitions, stop at the first demand that cannot be satisfied; the first requests waiters - // are covered by in-flight connects: they can be granted but no connection is created for them + // are covered by in-flight connects: they can be granted but no connection is created for them. + // The reconnection strategy suspends connect attempts after a failure + boolean suspended = suspendedUntilNanos != 0; int pos = 0; PoolWaiter next = waiters.peek(); while (true) { @@ -435,7 +465,7 @@ public void run() { lease.emit(); } }; - } else if (pos >= requests && capacity < maxCapacity) { + } else if (pos >= requests && capacity < maxCapacity && !suspended) { // 2. Try create connection, the waiter joins the covered prefix of the wait queue capacity += waiter.capacity; ContextInternal connectionContext = contextProvider.apply(waiter.context); @@ -579,6 +609,7 @@ public Task execute(DefaultConnectionPool pool) { slot.usage = 0; pool.requests--; pool.capacity += (capacity - initialCapacity); + pool.connectCount++; if (pool.closed) { return new Task() { @Override diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java index 6c205aaccc2..8df8248be9f 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java @@ -1293,5 +1293,13 @@ ConnectionRequest assertRequest() { Assert.assertNotNull(request); return request; } + + void assertNoRequest() { + Assert.assertNull(requests.peek()); + } + + boolean hasRequest() { + return requests.peek() != null; + } } } diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java index cbfd844a61c..b45870c5609 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java @@ -68,6 +68,75 @@ public void testStaleConnectionEviction() throws Exception { await(); } + @Test + public void testConnectRetryDelay() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + DefaultConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 1 }) + .withMaxWaiters(10) + .withConnectRetryDelay(Duration.ofMillis(20)) + .build(); + pool.acquire(context, 0, (res, err) -> { + // Fails with the connect failure + }); + AtomicBoolean served = new AtomicBoolean(); + Connection expected = new Connection(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + Assert.assertSame(expected, lease.get()); + served.set(true); + })); + mgr.assertRequest().fail(new Exception("not yet")); + // The connect attempts are suspended + pool.refresh(); + mgr.assertNoRequest(); + // Until the delay has passed + assertWaitUntil(() -> { + pool.refresh(); + return mgr.hasRequest(); + }); + mgr.assertRequest().connect(expected, 0); + assertWaitUntil(served::get); + } + + @Test + public void testConnectSuccessClearsRetryDelay() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + DefaultConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 2 }) + .withMaxWaiters(10) + .withConnectRetryDelay(Duration.ofSeconds(10)) + .build(); + pool.acquire(context, 0, (res, err) -> { + // Fails with the connect failure + }); + Connection conn1 = new Connection(); + AtomicBoolean served = new AtomicBoolean(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + Assert.assertSame(conn1, lease.get()); + served.set(true); + })); + ConnectionRequest request1 = mgr.assertRequest(); + ConnectionRequest request2 = mgr.assertRequest(); + // The failure triggers the delay + request1.fail(new Exception("failure")); + mgr.assertNoRequest(); + // A third acquisition falls in the wait queue, the delay suspends the connect + Connection conn2 = new Connection(); + AtomicBoolean served2 = new AtomicBoolean(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + Assert.assertSame(conn2, lease.get()); + served2.set(true); + })); + mgr.assertNoRequest(); + // The success clears the delay: it serves the covered waiter and connects for the waiting one + request2.connect(conn1, 0); + assertWaitUntil(served::get); + mgr.assertRequest().connect(conn2, 0); + assertWaitUntil(served2::get); + } + @Test public void testAcquireTimeout() throws Exception { ContextInternal context = vertx.createEventLoopContext(); From b215b3de56e397ff933f30fbdf57c7ac3c94dd89 Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Thu, 26 Nov 2026 09:22:33 +0100 Subject: [PATCH 14/18] Minimum pool size Motivation: Maintain a warm set of connections without demand, e.g. after start-up or a back-end restart. Changes: The builder configures minimum sizes, a default kind and a context supplier for demand-less connects. The minimum sizes are normalized to a minimum capacity, the maximum of minSizes[i] * capacityFactors[i]: each entry expresses the same floor in its kind units, like the maximum sizes. At the end of each execution round, the Cleanup final action asks the pool to satisfy the minimum capacity, creating one connection at a time of the default kind with the supplied context, when no connect is in flight: the actual weight of a connection is known on connect success only, connecting one at a time avoids overshooting the capacity. A floor connect counts as connecting - the requests field is renamed to connecting, requests is too close to HTTP - covering waiters arriving while it is in flight. The reconnection strategy paces the floor retries, hence a minimum requires a connect retry delay, enforced with the other guards by the constructor with explaining messages. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../internal/pool/DefaultConnectionPool.java | 106 +++++++++++-- .../tests/pool/DefaultConnectionPoolTest.java | 142 ++++++++++++++++++ 2 files changed, 234 insertions(+), 14 deletions(-) diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java index 4863271f3d6..5982ab46310 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java @@ -23,6 +23,7 @@ import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; +import java.util.function.Supplier; import java.util.function.Predicate; /** @@ -198,7 +199,7 @@ public long concurrency() { private final TaskList tasks; private final List> admitted; - private int requests; + private int connecting; // The recorded connect failure private Throwable failureCause; @@ -216,6 +217,13 @@ public long concurrency() { // against a single timestamp, assuming tasks execute quickly private long roundNanos; + // The minimum capacity, computed from the minimum sizes: missing connections are created at + // the end of each execution round with the supplied connection properties, paced by the + // reconnection strategy + private final int minCapacity; + private final int defaultKind; + private final Supplier contextSupplier; + // Whether the next progress is the first of the execution round private boolean first = true; @@ -224,7 +232,7 @@ public static DefaultConnectionPool pool(PoolConnector connector, int[ } public static DefaultConnectionPool pool(PoolConnector connector, int[] maxSizes, int maxWaiters) { - return new DefaultConnectionPool<>(connector, maxSizes, maxWaiters, null); + return new DefaultConnectionPool<>(connector, maxSizes, maxWaiters, null, null, 0, null); } public static Builder builder(PoolConnector connector) { @@ -237,6 +245,9 @@ public static class Builder { private int[] maxSizes; private int maxWaiters = -1; private Duration connectRetryDelay; + private int[] minSizes; + private int defaultKind; + private Supplier contextSupplier; Builder(PoolConnector connector) { this.connector = Objects.requireNonNull(connector); @@ -257,16 +268,32 @@ public Builder withConnectRetryDelay(Duration connectRetryDelay) { return this; } + public Builder withMinSizes(int[] minSizes) { + this.minSizes = minSizes; + return this; + } + + public Builder withDefaultKind(int defaultKind) { + this.defaultKind = defaultKind; + return this; + } + + public Builder withContextSupplier(Supplier contextSupplier) { + this.contextSupplier = contextSupplier; + return this; + } + public DefaultConnectionPool build() { - return new DefaultConnectionPool<>(connector, Objects.requireNonNull(maxSizes), maxWaiters, connectRetryDelay); + return new DefaultConnectionPool<>(connector, Objects.requireNonNull(maxSizes), maxWaiters, connectRetryDelay, minSizes, defaultKind, contextSupplier); } } DefaultConnectionPool(PoolConnector connector, int[] maxSizes) { - this(connector, maxSizes, -1, null); + this(connector, maxSizes, -1, null, null, 0, null); } - DefaultConnectionPool(PoolConnector connector, int[] maxSizes, int maxWaiters, Duration connectRetryDelay) { + DefaultConnectionPool(PoolConnector connector, int[] maxSizes, int maxWaiters, Duration connectRetryDelay, + int[] minSizes, int defaultKind, Supplier contextSupplier) { int[] capacities = new int[maxSizes.length]; int maxCapacity = 1; @@ -282,6 +309,29 @@ public DefaultConnectionPool build() { for (int i = 0;i < maxSizes.length;i++) { capacities[i] = maxCapacity / maxSizes[i]; } + int minCapacity = 0; + if (minSizes != null) { + if (minSizes.length != maxSizes.length) { + throw new IllegalArgumentException("Minimum sizes must have one size per kind, like the maximum sizes"); + } + for (int i = 0;i < minSizes.length;i++) { + if (minSizes[i] < 0 || minSizes[i] > maxSizes[i]) { + throw new IllegalArgumentException("Minimum size must be between 0 and the maximum size of its kind"); + } + minCapacity = Math.max(minCapacity, minSizes[i] * capacities[i]); + } + } + if (defaultKind < 0 || defaultKind >= maxSizes.length) { + throw new IllegalArgumentException("Default kind must be an index in the maximum sizes"); + } + if (minCapacity > 0) { + if (contextSupplier == null) { + throw new IllegalArgumentException("A minimum pool size requires a context supplier"); + } + if (connectRetryDelay == null) { + throw new IllegalArgumentException("A minimum pool size requires a connect retry delay"); + } + } this.capacityFactors = capacities; this.connector = connector; @@ -299,6 +349,9 @@ public DefaultConnectionPool build() { this.tasks = new TaskList(); this.admitted = new ArrayList<>(); this.retryDelayNanos = connectRetryDelay == null ? 0L : connectRetryDelay.toNanos(); + this.minCapacity = minCapacity; + this.defaultKind = defaultKind; + this.contextSupplier = contextSupplier; } @Override @@ -325,8 +378,9 @@ private static class Cleanup implements Executor.Action pool) { + Task head = pool.last(); pool.first = true; - return null; + return head; } } @@ -428,7 +482,7 @@ public void run() { // Satisfy the demand: peek from the wait queue, when it is exhausted peek from the submitted - // acquisitions, stop at the first demand that cannot be satisfied; the first requests waiters + // acquisitions, stop at the first demand that cannot be satisfied; the first connecting waiters // are covered by in-flight connects: they can be granted but no connection is created for them. // The reconnection strategy suspends connect attempts after a failure boolean suspended = suspendedUntilNanos != 0; @@ -465,13 +519,13 @@ public void run() { lease.emit(); } }; - } else if (pos >= requests && capacity < maxCapacity && !suspended) { + } else if (pos >= connecting && capacity < maxCapacity && !suspended) { // 2. Try create connection, the waiter joins the covered prefix of the wait queue capacity += waiter.capacity; ContextInternal connectionContext = contextProvider.apply(waiter.context); Slot slot2 = new Slot<>(this, connectionContext, size, waiter.capacity); slots[size++] = slot2; - requests++; + connecting++; pos++; task = new Task() { @Override @@ -494,7 +548,7 @@ public void run() { lease.emit(); } }; - } else if (pos < requests) { + } else if (pos < connecting) { // 4. Covered by an in-flight connect, wait for it pos++; } else if (submission) { @@ -573,6 +627,30 @@ public void run() { } } + private Task last() { + // Satisfy the minimum capacity after all demand is served, creating one connection at a + // time of the default kind with the supplied context, when no connect is in flight: the + // actual weight of a connection is known on connect success only, connecting one at a time + // avoids overshooting the capacity. A floor connect counts as connecting, covering + // waiters arriving while it is in flight. The reconnection strategy paces the floor retries + boolean suspended = suspendedUntilNanos != 0; + if (!closed && !suspended && connecting == 0 && capacity < minCapacity) { + int floorCapacity = capacityFactors[defaultKind]; + capacity += floorCapacity; + ContextInternal connectionContext = contextProvider.apply(contextSupplier.get()); + Slot slot = new Slot<>(this, connectionContext, size, floorCapacity); + slots[size++] = slot; + connecting++; + return new Task() { + @Override + public void run() { + connect(slot); + } + }; + } + return null; + } + public int size() { return size; } @@ -607,7 +685,7 @@ public Task execute(DefaultConnectionPool pool) { slot.concurrency = result.concurrency(); slot.capacity = capacity; slot.usage = 0; - pool.requests--; + pool.connecting--; pool.capacity += (capacity - initialCapacity); pool.connectCount++; if (pool.closed) { @@ -633,7 +711,7 @@ public ConnectFailed(Slot removed, Throwable cause) { } public Task execute(DefaultConnectionPool pool) { - pool.requests--; + pool.connecting--; Task task = new Task() { @Override public void run() { @@ -905,7 +983,7 @@ private void recycle(LeaseImpl lease) { } public int waiters() { - return Math.max(0, waiters.size() - requests); + return Math.max(0, waiters.size() - connecting); } public int capacity() { @@ -914,7 +992,7 @@ public int capacity() { @Override public int requests() { - return requests; + return connecting; } private static class Close implements Executor.Action> { diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java index b45870c5609..9f137b48fd4 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java @@ -195,6 +195,148 @@ public void onTimeout(PoolWaiter waiter) { Assert.assertTrue(timedOut.get()); } + @Test + public void testMinSizeRequiresConnectRetryDelay() { + ConnectionManager mgr = new ConnectionManager(); + try { + DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 5 }) + .withMinSizes(new int[] { 1 }) + .withContextSupplier(() -> vertx.createEventLoopContext()) + .build(); + Assert.fail(); + } catch (IllegalArgumentException expected) { + } + } + + @Test + public void testMinSize() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + DefaultConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 5 }) + .withMinSizes(new int[] { 3 }) + .withContextSupplier(() -> context) + .withConnectRetryDelay(Duration.ofSeconds(10)) + .build(); + // The floor is satisfied one connection at a time from the first execution round, extra + // refreshes do not trigger extra connect requests while one is in flight + pool.refresh(); + pool.refresh(); + pool.refresh(); + ConnectionRequest request = mgr.assertRequest(); + mgr.assertNoRequest(); + request.connect(new Connection(), 0); + mgr.assertRequest().connect(new Connection(), 0); + mgr.assertRequest().connect(new Connection(), 0); + mgr.assertNoRequest(); + assertWaitUntil(() -> pool.size() == 3); + // An acquisition is served from the pooled connections + AtomicBoolean served = new AtomicBoolean(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + served.set(true); + })); + assertWaitUntil(served::get); + mgr.assertNoRequest(); + } + + @Test + public void testMinSizeCoversWaiter() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + DefaultConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 5 }) + .withMinSizes(new int[] { 1 }) + .withContextSupplier(() -> context) + .withConnectRetryDelay(Duration.ofSeconds(10)) + .build(); + pool.refresh(); + ConnectionRequest request = mgr.assertRequest(); + // A waiter arriving while the floor connect is in flight is covered by it + Connection expected = new Connection(); + AtomicBoolean served = new AtomicBoolean(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + Assert.assertSame(expected, lease.get()); + served.set(true); + })); + mgr.assertNoRequest(); + request.connect(expected, 0); + assertWaitUntil(served::get); + Assert.assertEquals(1, pool.size()); + } + + @Test + public void testMinSizeConnectRetryDelay() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + DefaultConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 5 }) + .withMinSizes(new int[] { 1 }) + .withContextSupplier(() -> context) + .withConnectRetryDelay(Duration.ofMillis(20)) + .build(); + pool.refresh(); + mgr.assertRequest().fail(new Exception("not yet")); + // The failure suspends the floor + pool.refresh(); + mgr.assertNoRequest(); + // Until the delay has passed + assertWaitUntil(() -> { + pool.refresh(); + return mgr.hasRequest(); + }); + // The retry fails: the floor is suspended again + mgr.assertRequest().fail(new Exception("not yet")); + pool.refresh(); + mgr.assertNoRequest(); + // The next retry succeeds + assertWaitUntil(() -> { + pool.refresh(); + return mgr.hasRequest(); + }); + Connection conn = new Connection(); + mgr.assertRequest().connect(conn, 0); + assertWaitUntil(() -> pool.size() == 1); + } + + @Test + public void testMinCapacity() { + // HTTP/1 floor: an HTTP/1 back-end converges to the minimum connections one at a time, + // a single HTTP/2 connection satisfies the floor without overshooting + assertMinCapacity(new int[] { 5, 1 }, new int[] { 3, 0 }, 0, 0, 3, 3); + assertMinCapacity(new int[] { 5, 1 }, new int[] { 3, 0 }, 0, 1, 1, 5); + assertMinCapacity(new int[] { 5, 1 }, new int[] { 3, 0 }, 1, 0, 3, 3); + assertMinCapacity(new int[] { 5, 1 }, new int[] { 3, 0 }, 1, 1, 1, 5); + // HTTP/2 floor: an HTTP/1 back-end converges from below to the equivalent capacity, an + // HTTP/2 back-end is satisfied by one connection + assertMinCapacity(new int[] { 5, 1 }, new int[] { 0, 1 }, 0, 0, 5, 5); + assertMinCapacity(new int[] { 5, 1 }, new int[] { 0, 1 }, 0, 1, 1, 5); + assertMinCapacity(new int[] { 5, 1 }, new int[] { 0, 1 }, 1, 0, 5, 5); + assertMinCapacity(new int[] { 5, 1 }, new int[] { 0, 1 }, 1, 1, 1, 5); + } + + private void assertMinCapacity(int[] maxSizes, int[] minSizes, int defaultKind, int connectKind, + int expectedSize, int expectedCapacity) { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + DefaultConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(maxSizes) + .withMinSizes(minSizes) + .withDefaultKind(defaultKind) + .withContextSupplier(() -> context) + .withConnectRetryDelay(Duration.ofSeconds(10)) + .build(); + while (true) { + pool.refresh(); + if (!mgr.hasRequest()) { + break; + } + mgr.assertRequest().connect(new Connection(), connectKind); + } + Assert.assertEquals(expectedSize, pool.size()); + Assert.assertEquals(expectedCapacity, pool.capacity()); + } + @Override protected ConnectionPool pool(PoolConnector connector, int[] maxSizes) { return DefaultConnectionPool.pool(connector, maxSizes); From abfc7857f4fcd052ae4e3fe7c8d1738f4110d6c8 Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Thu, 26 Nov 2026 10:35:00 +0100 Subject: [PATCH 15/18] Single admission and rejection of the submissions Motivation: The satisfaction loop bound-checks and rejects an admitted submission it cannot serve, duplicating the logic of the move that follows the loop. Changes: When nothing is possible for a submission, the loop gives it back to the submitted queue and stops; the move below the loop is the single place admitting the remaining submissions in the wait queue or rejecting them over the bound. A submission served by a grant or a connect remains exempted from the bound. The admitted submissions are tracked with a deque, the give back drops the last one. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../internal/pool/DefaultConnectionPool.java | 30 ++++++++----------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java index 5982ab46310..15fdc119dd9 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java @@ -18,6 +18,8 @@ import java.util.AbstractList; import java.util.ArrayList; import java.util.Iterator; +import java.util.ArrayDeque; +import java.util.Deque; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; @@ -197,7 +199,7 @@ public long concurrency() { // Scratch structures of the progress, allocated once and reused between runs: the executor // guarantees a single progress at a time private final TaskList tasks; - private final List> admitted; + private final Deque> admitted; private int connecting; @@ -347,7 +349,7 @@ public DefaultConnectionPool build() { this.submitted = new Waiters<>(); this.waiters = new Waiters<>(); this.tasks = new TaskList(); - this.admitted = new ArrayList<>(); + this.admitted = new ArrayDeque<>(); this.retryDelayNanos = connectRetryDelay == null ? 0L : connectRetryDelay.toNanos(); this.minCapacity = minCapacity; this.defaultKind = defaultKind; @@ -496,8 +498,9 @@ public void run() { waiter = next; next = waiters.next(next); } else if ((waiter = submitted.poll()) != null) { - // Admit a submission in the wait queue, the bound is enforced only when it remains waiting: - // a submission served by a grant or a connect is exempted, like the existing pool + // Admit a submission in the wait queue, the bound is enforced by the move below only + // when it remains waiting: a submission served by a grant or a connect is exempted, + // like the existing pool submission = true; waiters.addLast(waiter); admitted.add(waiter); @@ -552,19 +555,12 @@ public void run() { // 4. Covered by an in-flight connect, wait for it pos++; } else if (submission) { - // 5. The submission remains waiting, reject it when the wait queue exceeds the bound - if (maxWaiters != -1 && waiters.size() > maxWaiters) { - waiters.remove(waiter); - task = new Task() { - @Override - public void run() { - Future> fut = waiter.context.failedFuture(new ConnectionPoolTooBusyException("Connection pool reached max wait queue size of " + maxWaiters)); - fut.onComplete(waiter.handler); - } - }; - } else { - pos++; - } + // 5. Nothing is possible for the submission: give it back, the move below admits or + // rejects it with the remaining submissions + waiters.remove(waiter); + admitted.removeLast(); + submitted.addFirst(waiter); + break; } else { // 6. No satisfaction is possible anymore break; From ad4352b48b3cbc0423ace279792ed1f7f0f37aec Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Thu, 26 Nov 2026 22:46:05 +0100 Subject: [PATCH 16/18] Connection checker Motivation: The pool checks the connection validity with PoolConnector#isValid: the connector composes the transport validity with the expiration policy, e.g. the HTTP client connector checks the connection and the maximum lifetime. The connection is not aware of the timing in the pool and the pool is not aware of the expiration policy. Changes: The builder configures a connection checker predicate owning the whole connection validity, defaulting to always valid; the pool does not use PoolConnector#isValid anymore, kept on the connector contract for SimpleConnectionPool. The beginning of the execution round evicts the idle connections that do not pass the check, before any demand is served: a connection checked at the beginning of a round is assumed valid for the round, otherwise it is caught in the next round; a busy connection finishes its leases. An evicted floor connection is refilled at the end of the same round, rotating the connection. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../internal/pool/DefaultConnectionPool.java | 26 +++++++-- .../tests/pool/DefaultConnectionPoolTest.java | 58 ++++++++++++++++++- 2 files changed, 77 insertions(+), 7 deletions(-) diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java index 15fdc119dd9..bdb2a265f4f 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java @@ -25,8 +25,8 @@ import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; -import java.util.function.Supplier; import java.util.function.Predicate; +import java.util.function.Supplier; /** *

The pool is a state machine that maintains a queue of waiters and a list of connections. @@ -219,6 +219,12 @@ public long concurrency() { // against a single timestamp, assuming tasks execute quickly private long roundNanos; + // The connection checker owns the whole connection validity, transport validity and + // expiration policy, the pool does not use PoolConnector#isValid: an idle connection that + // does not pass the check is evicted and closed at the beginning of the execution round, + // before any demand is served + private final Predicate connectionChecker; + // The minimum capacity, computed from the minimum sizes: missing connections are created at // the end of each execution round with the supplied connection properties, paced by the // reconnection strategy @@ -234,7 +240,7 @@ public static DefaultConnectionPool pool(PoolConnector connector, int[ } public static DefaultConnectionPool pool(PoolConnector connector, int[] maxSizes, int maxWaiters) { - return new DefaultConnectionPool<>(connector, maxSizes, maxWaiters, null, null, 0, null); + return new DefaultConnectionPool<>(connector, maxSizes, maxWaiters, null, null, null, 0, null); } public static Builder builder(PoolConnector connector) { @@ -248,6 +254,7 @@ public static class Builder { private int maxWaiters = -1; private Duration connectRetryDelay; private int[] minSizes; + private Predicate connectionChecker; private int defaultKind; private Supplier contextSupplier; @@ -270,6 +277,11 @@ public Builder withConnectRetryDelay(Duration connectRetryDelay) { return this; } + public Builder withConnectionChecker(Predicate connectionChecker) { + this.connectionChecker = connectionChecker; + return this; + } + public Builder withMinSizes(int[] minSizes) { this.minSizes = minSizes; return this; @@ -286,16 +298,17 @@ public Builder withContextSupplier(Supplier contextSupplier) } public DefaultConnectionPool build() { - return new DefaultConnectionPool<>(connector, Objects.requireNonNull(maxSizes), maxWaiters, connectRetryDelay, minSizes, defaultKind, contextSupplier); + return new DefaultConnectionPool<>(connector, Objects.requireNonNull(maxSizes), maxWaiters, connectRetryDelay, connectionChecker, minSizes, defaultKind, contextSupplier); } } DefaultConnectionPool(PoolConnector connector, int[] maxSizes) { - this(connector, maxSizes, -1, null, null, 0, null); + this(connector, maxSizes, -1, null, null, null, 0, null); } DefaultConnectionPool(PoolConnector connector, int[] maxSizes, int maxWaiters, Duration connectRetryDelay, - int[] minSizes, int defaultKind, Supplier contextSupplier) { + Predicate connectionChecker, int[] minSizes, int defaultKind, + Supplier contextSupplier) { int[] capacities = new int[maxSizes.length]; int maxCapacity = 1; @@ -351,6 +364,7 @@ public DefaultConnectionPool build() { this.tasks = new TaskList(); this.admitted = new ArrayDeque<>(); this.retryDelayNanos = connectRetryDelay == null ? 0L : connectRetryDelay.toNanos(); + this.connectionChecker = connectionChecker == null ? c -> true : connectionChecker; this.minCapacity = minCapacity; this.defaultKind = defaultKind; this.contextSupplier = contextSupplier; @@ -443,7 +457,7 @@ public void run() { } for (int i = size - 1;i >= 0;i--) { Slot slot = slots[i]; - if (slot.connection != null && slot.usage == 0 && !connector.isValid(slot.connection)) { + if (slot.connection != null && slot.usage == 0 && !connectionChecker.test(slot.connection)) { C connection = slot.connection; removeSlot(slot); Task task = new Task() { diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java index 9f137b48fd4..1c3b0668878 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java @@ -11,6 +11,7 @@ package io.vertx.tests.pool; import io.vertx.core.internal.ContextInternal; +import io.vertx.core.internal.pool.Lease; import io.vertx.core.internal.pool.ConnectionPool; import io.vertx.core.internal.pool.PoolConnector; import io.vertx.core.internal.pool.PoolWaiter; @@ -22,6 +23,7 @@ import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; public class DefaultConnectionPoolTest extends ConnectionPoolTest { @@ -29,7 +31,11 @@ public class DefaultConnectionPoolTest extends ConnectionPoolTest { public void testStaleConnectionEviction() throws Exception { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = pool(mgr, new int[] { 2 }); + // The checker owns the whole connection validity, the pool does not use PoolConnector#isValid + ConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 2 }) + .withConnectionChecker(conn -> conn.valid) + .build(); Connection conn1 = new Connection(); Connection conn2 = new Connection(); CountDownLatch latch = new CountDownLatch(2); @@ -68,6 +74,56 @@ public void testStaleConnectionEviction() throws Exception { await(); } + @Test + public void testInvalidConnectionRetainedWhileBusy() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 2 }) + .withConnectionChecker(conn -> conn.valid) + .build(); + Connection conn = new Connection(); + AtomicReference> leaseRef = new AtomicReference<>(); + pool.acquire(context, 0, TestUtils.onSuccess2(leaseRef::set)); + mgr.assertRequest().connect(conn, 0); + assertWaitUntil(() -> leaseRef.get() != null); + // A busy connection finishes its leases + conn.valid = false; + pool.refresh(); + Assert.assertEquals(1, pool.size()); + Assert.assertFalse(conn.closed); + // Once idle it is evicted + leaseRef.get().recycle(); + assertWaitUntil(() -> pool.size() == 0); + Assert.assertTrue(conn.closed); + mgr.assertNoRequest(); + } + + @Test + public void testConnectionRotation() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 2 }) + .withMinSizes(new int[] { 1 }) + .withContextSupplier(() -> context) + .withConnectRetryDelay(Duration.ofSeconds(10)) + .withConnectionChecker(conn -> conn.valid) + .build(); + pool.refresh(); + Connection conn1 = new Connection(); + mgr.assertRequest().connect(conn1, 0); + assertWaitUntil(() -> pool.size() == 1); + // Evicting the invalid connection refills the floor in the same round: rotation + conn1.valid = false; + pool.refresh(); + Connection conn2 = new Connection(); + mgr.assertRequest().connect(conn2, 0); + Assert.assertTrue(conn1.closed); + assertWaitUntil(() -> pool.size() == 1); + mgr.assertNoRequest(); + } + @Test public void testConnectRetryDelay() throws Exception { ContextInternal context = vertx.createEventLoopContext(); From 88a799b05974a84410400924ed575855a029bccf Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Tue, 1 Dec 2026 11:32:26 +0100 Subject: [PATCH 17/18] Connection kind change Motivation: The kind of a connection can be discovered after the connect success, e.g. a clear text upgrade resolving to HTTP/1.1: the provisional classification must be adjusted. Changes: PoolConnector.Listener gets a default onKindChange signal: the pool adjusts the connection capacity to the new kind and makes progress, using or returning the capacity difference. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../internal/pool/DefaultConnectionPool.java | 33 +++++++++++++++++++ .../core/internal/pool/PoolConnector.java | 9 +++++ .../tests/pool/DefaultConnectionPoolTest.java | 27 +++++++++++++++ 3 files changed, 69 insertions(+) diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java index bdb2a265f4f..2df023466a6 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java @@ -139,6 +139,11 @@ public void onRemove() { pool.remove(this); } + @Override + public void onKindChange(int kind) { + pool.setKind(this, kind); + } + @Override public void onConcurrencyChange(long concurrency) { pool.setConcurrency(this, concurrency); @@ -710,6 +715,30 @@ public void run() { } } + private static class KindChange implements Executor.Action> { + + private final Slot slot; + private final int kind; + + private KindChange(Slot slot, int kind) { + this.slot = slot; + this.kind = kind; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (slot.connection != null) { + int capacity = pool.capacityFactors[kind]; + pool.capacity += capacity - slot.capacity; + slot.capacity = capacity; + } + if (pool.closed) { + return null; + } + return pool.progress(); + } + } + private static class ConnectFailed implements Executor.Action> { private final Slot removed; @@ -781,6 +810,10 @@ public Task execute(DefaultConnectionPool pool) { } } + private void setKind(Slot slot, int kind) { + execute(new KindChange<>(slot, kind)); + } + private void setConcurrency(Slot slot, long concurrency) { execute(new SetConcurrency<>(slot, concurrency)); } diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolConnector.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolConnector.java index 6bfab1ca2dc..b0b70400c41 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolConnector.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolConnector.java @@ -68,5 +68,14 @@ interface Listener { */ void onConcurrencyChange(long concurrency); + /** + * Signals the connection kind changed to the {@code kind} value, e.g. after a clear-text + * upgrade resolution: the pool adjusts the connection capacity accordingly. + * + * @param kind the connection kind, an index in the max size array the pool is constructed with + */ + default void onKindChange(int kind) { + } + } } diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java index 1c3b0668878..222e8e8b2a9 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java @@ -193,6 +193,33 @@ public void testConnectSuccessClearsRetryDelay() throws Exception { assertWaitUntil(served2::get); } + @Test + public void testKindChange() { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = pool(mgr, new int[] { 5, 1 }); + Connection conn1 = new Connection(); + AtomicBoolean served = new AtomicBoolean(); + pool.acquire(context, 1, TestUtils.onSuccess2(lease -> { + served.set(true); + })); + ConnectionRequest request1 = mgr.assertRequest(); + // A second acquisition waits: the pool is at capacity + Connection conn2 = new Connection(); + AtomicBoolean served2 = new AtomicBoolean(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + Assert.assertSame(conn2, lease.get()); + served2.set(true); + })); + request1.connect(conn1, 1); + assertWaitUntil(served::get); + mgr.assertNoRequest(); + // The kind change returns the capacity: the pool connects for the waiting acquisition + request1.listener.onKindChange(0); + mgr.assertRequest().connect(conn2, 0); + assertWaitUntil(served2::get); + } + @Test public void testAcquireTimeout() throws Exception { ContextInternal context = vertx.createEventLoopContext(); From ed55745665f0354ff6bf3e5bbb17ba2eda539642 Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Tue, 1 Dec 2026 10:10:54 +0100 Subject: [PATCH 18/18] Use DefaultConnectionPool for the HTTP client Motivation: Validate the new pool with the HTTP client, as an iso feature implementation. Changes: SharedHttpClientConnectionGroup builds a DefaultConnectionPool. The acquisition timeout moves into the pool: the request timeout is the acquire timeout and the timer machinery is removed, the pool signals onTimeout. The periodic expiration check becomes a pool refresh: the connection checker owns the whole connection validity - the transport validity composed with the maximum lifetime - and the pool closes the evicted connections with the connector close; the evict method and PoolConnector#isValid are not used anymore, isValid throws UnsupportedOperationException. A connection established after its waiter timed out is preserved in the pool and reused by the next acquisition instead of being closed - a timeout is a statement about the waiter, not about the connection; the test asserting the former behavior now asserts the reuse. A pending clear text upgrade is classified with the HTTP/2 intent, kind 1 with a concurrency of one: the pool has no capacity to dial into for the queued waiters, they wait, covered - the previous pool never dialed for queued waiters, masking the classification by the materialized HTTP/1.1 version. A successful upgrade raises the concurrency with onConcurrencyChange; a rejected upgrade reclassifies the connection with onKindChange, returning the capacity so the pool grows to the HTTP/1 maximum size instead of staying capped by the HTTP/2 one. Assisted-by: Anthropic Claude (claude-fable-5) Signed-off-by: Julien Viet --- .../impl/SharedHttpClientConnectionGroup.java | 77 ++++++++++--------- .../tcp/Http2UpgradeClientConnection.java | 22 ++++++ .../io/vertx/tests/http/Http1xProxyTest.java | 27 ++++--- .../java/io/vertx/tests/http/Http2Test.java | 29 +++++++ 4 files changed, 108 insertions(+), 47 deletions(-) diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/SharedHttpClientConnectionGroup.java b/vertx-core/src/main/java/io/vertx/core/http/impl/SharedHttpClientConnectionGroup.java index ce9c6d38b14..7bf6cab05ba 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/SharedHttpClientConnectionGroup.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/SharedHttpClientConnectionGroup.java @@ -16,8 +16,10 @@ import io.vertx.core.internal.ContextInternal; import io.vertx.core.impl.NoStackTraceTimeoutException; import io.vertx.core.internal.http.HttpClientTransport; +import io.vertx.core.http.impl.tcp.Http2UpgradeClientConnection; import io.vertx.core.internal.pool.ConnectResult; import io.vertx.core.internal.pool.ConnectionPool; +import io.vertx.core.internal.pool.DefaultConnectionPool; import io.vertx.core.internal.pool.PoolConnection; import io.vertx.core.internal.pool.PoolConnector; import io.vertx.core.internal.pool.Lease; @@ -29,6 +31,7 @@ import io.vertx.core.spi.metrics.HttpClientMetrics; import io.vertx.core.spi.metrics.PoolMetrics; +import java.time.Duration; import java.util.List; import java.util.Objects; import java.util.function.BiFunction; @@ -102,43 +105,25 @@ private class Request implements PoolWaiter.Listener, Comp private final ContextInternal context; private final long timeout; private final Promise> promise; - private long timerID; Request(ContextInternal context, long timeout, Promise> promise) { this.context = context; this.timeout = timeout; this.promise = promise; - this.timerID = -1L; } @Override - public void onEnqueue(PoolWaiter waiter) { - onConnect(waiter); - } - - @Override - public void onConnect(PoolWaiter waiter) { - if (timeout > 0L && timerID == -1L) { - timerID = context.setTimer(timeout, id -> { - pool.pool.cancel(waiter, (res, err) -> { - if (err == null && res) - promise.fail(new NoStackTraceTimeoutException("The timeout of " + timeout + " ms has been exceeded when getting a connection to " + server)); - }); - }); - } + public void onTimeout(PoolWaiter waiter) { + promise.fail(new NoStackTraceTimeoutException("The timeout of " + timeout + " ms has been exceeded when getting a connection to " + server)); } @Override public void complete(Lease result, Throwable failure) { - if (timerID >= 0 && !context.owner().cancelTimer(timerID)) { - result.recycle(); - } else { - promise.complete(result, failure); - } + promise.complete(result, failure); } void acquire() { - pool.acquire(context,this, promise); + pool.acquire(context, this, timeout, promise); } } @@ -212,8 +197,12 @@ static class Pool implements PoolConnector { this.maxLifetimeMillis = maxLifetimeMillis; this.connectParams = connectParams; this.poolKind = initialPoolKind; - this.pool = ConnectionPool - .pool(this, new int[]{http1MaxSize, http2MaxSize}, queueMaxSize) + this.pool = DefaultConnectionPool + .builder(this) + .withMaxSizes(new int[]{http1MaxSize, http2MaxSize}) + .withMaxWaiters(queueMaxSize) + .withConnectionChecker(this::checkConnection) + .build() .connectionSelector(LIFO_SELECTOR) .contextProvider(contextProvider); } @@ -231,8 +220,12 @@ static class Pool implements PoolConnector { this.maxLifetimeMillis = maxLifetimeMillis; this.connectParams = connectParams; this.poolKind = 0; - this.pool = ConnectionPool - .pool(this, new int[]{http3MaxSize}, queueMaxSize) + this.pool = DefaultConnectionPool + .builder(this) + .withMaxSizes(new int[]{http3MaxSize}) + .withMaxWaiters(queueMaxSize) + .withConnectionChecker(this::checkConnection) + .build() .connectionSelector(LIFO_SELECTOR) .contextProvider(contextProvider); } @@ -249,7 +242,17 @@ public Future> connect(ContextInternal conte connection.concurrencyChangeHandler(listener::onConcurrencyChange); owner.init(connection); long capacity = connection.concurrency(); - int idx = connection.protocolVersion() != HttpVersion.HTTP_2 ? 0 : 1; + int idx; + if (connection instanceof Http2UpgradeClientConnection && ((Http2UpgradeClientConnection)connection).upgradePending()) { + // The clear-text upgrade rides on the first request: classify with the HTTP/2 intent + // so the pool does not dial into phantom HTTP/1 headroom, the concurrency raises with + // onConcurrencyChange when the upgrade succeeds; reclassify when it is rejected, + // returning the capacity so the pool can dial more HTTP/1 connections + idx = 1; + ((Http2UpgradeClientConnection)connection).upgradeRejectedHandler(v -> listener.onKindChange(0)); + } else { + idx = connection.protocolVersion() != HttpVersion.HTTP_2 ? 0 : 1; + } return new ConnectResult<>(connection, capacity, idx); }); if (owner.exceptionHandler != null) { @@ -264,20 +267,24 @@ public Future> connect(ContextInternal conte @Override public boolean isValid(HttpClientConnection connection) { + throw new UnsupportedOperationException(); + } + + private boolean checkConnection(HttpClientConnection connection) { return connection.isValid() && (maxLifetimeMillis == 0L || (System.currentTimeMillis() - connection.creationTimestamp()) <= maxLifetimeMillis); } + @Override + public void close(HttpClientConnection connection) { + connection.close(); + } + void checkExpired() { - pool - .evict(c -> !isValid(c), (lst, err) -> { - if (err == null) { - lst.forEach(HttpConnection::close); - } - }); + pool.refresh(); } - void acquire(ContextInternal context, PoolWaiter.Listener listener, Promise> promise) { - pool.acquire(context, listener, poolKind, promise); + void acquire(ContextInternal context, PoolWaiter.Listener listener, long timeout, Promise> promise) { + pool.acquire(context, listener, poolKind, timeout > 0L ? Duration.ofMillis(timeout) : null, promise); } void close() { diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/tcp/Http2UpgradeClientConnection.java b/vertx-core/src/main/java/io/vertx/core/http/impl/tcp/Http2UpgradeClientConnection.java index 51c76708a26..b6634c37e81 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/tcp/Http2UpgradeClientConnection.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/tcp/Http2UpgradeClientConnection.java @@ -60,6 +60,7 @@ public class Http2UpgradeClientConnection implements io.vertx.core.http.impl.Htt private final ClientMetrics clientMetrics; private io.vertx.core.http.impl.HttpClientConnection current; private boolean upgradeProcessed; + private Handler upgradeRejectedHandler; private Handler closeHandler; private Handler shutdownHandler; @@ -83,6 +84,21 @@ public io.vertx.core.http.impl.HttpClientConnection unwrap() { return current; } + /** + * @return whether the clear-text upgrade has not been resolved yet + */ + public boolean upgradePending() { + return current instanceof Http1ClientConnection && !upgradeProcessed; + } + + /** + * Set the handler signalled when the clear-text upgrade is rejected and the connection remains HTTP/1.1. + */ + public Http2UpgradeClientConnection upgradeRejectedHandler(Handler handler) { + upgradeRejectedHandler = handler; + return this; + } + @Override public MultiMap newHttpRequestHeaders() { return current.newHttpRequestHeaders(); @@ -368,6 +384,7 @@ void handleUpgrade(io.vertx.core.http.impl.HttpClientConnection conn, HttpClient upgradedConnection.evictionHandler = null; upgradedConnection.concurrencyChangeHandler = null; upgradedConnection.invalidMessageHandler = null; + upgradedConnection.upgradeRejectedHandler = null; concurrencyChangeHandler.handle(conn.concurrency()); } @@ -418,6 +435,11 @@ public void upgradeAccepted(io.vertx.core.http.impl.HttpClientConnection connect public void upgradeRejected() { UpgradingStream.this.upgradeRejected = true; UpgradingStream.this.upgradedConnection.upgradeProcessed = true; + Handler handler = UpgradingStream.this.upgradedConnection.upgradeRejectedHandler; + UpgradingStream.this.upgradedConnection.upgradeRejectedHandler = null; + if (handler != null) { + handler.handle(null); + } } @Override public void upgradeFailure(Throwable cause) { diff --git a/vertx-core/src/test/java/io/vertx/tests/http/Http1xProxyTest.java b/vertx-core/src/test/java/io/vertx/tests/http/Http1xProxyTest.java index 2e821c38167..f76cee5ecde 100644 --- a/vertx-core/src/test/java/io/vertx/tests/http/Http1xProxyTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/http/Http1xProxyTest.java @@ -16,7 +16,6 @@ import io.vertx.core.http.*; import io.vertx.core.http.impl.CleanableHttpClient; import io.vertx.core.http.impl.HttpClientImpl; -import io.vertx.core.net.NetServer; import io.vertx.core.net.ProxyOptions; import io.vertx.core.net.ProxyType; import io.vertx.core.net.SocketAddress; @@ -37,7 +36,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; import static io.vertx.core.http.HttpMethod.GET; import static org.junit.Assert.*; @@ -635,11 +634,11 @@ private void testConnectTimeout(boolean shouldTimeout) throws Exception { @WithProxy(kind = ProxyKind.SOCKS5) @Test - public void testConnectionEstablishedAfterWaiterTimeoutIsClosed(Checkpoint checkpoint) throws Exception { - CountDownLatch latch = checkpoint.asLatch(2); - NetServer server = vertx.createNetServer(); - server.connectHandler(socket -> socket.closeHandler(v -> latch.countDown())); - server.listen(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST).await(); + public void testConnectionEstablishedAfterWaiterTimeoutIsPreserved() throws Exception { + AtomicInteger connections = new AtomicInteger(); + server.connectionHandler(conn -> connections.incrementAndGet()); + server.requestHandler(req -> req.response().end()); + startServer(); proxy.successDelayMillis(Duration.ofMillis(500)); client = vertx.createHttpClient(createBaseClientOptions() .setProxyOptions(new ProxyOptions() @@ -647,11 +646,15 @@ public void testConnectionEstablishedAfterWaiterTimeoutIsClosed(Checkpoint check .setHost(DEFAULT_HTTP_HOST) .setPort(proxy.port()) .setConnectTimeout(Duration.ofSeconds(5)))); - client.request(new RequestOptions(requestOptions).setConnectTimeout(100)) - .onComplete(ar -> { - assertTrue(ar.failed()); - latch.countDown(); - }); + // The connection established after the waiter timed out is preserved in the pool: the next + // request reuses it + assertThat(client.request(new RequestOptions(requestOptions).setConnectTimeout(100))) + .isFailure() + .compose(cause -> client.request(new RequestOptions(requestOptions))) + .compose(req -> req.send().compose(HttpClientResponse::end)) + .compose(v -> connections.get() == 1 ? Future.succeededFuture() + : Future.failedFuture(new AssertionError("Expected a single connection, got " + connections.get()))) + .await(); } @WithProxy(kind = ProxyKind.HTTP) diff --git a/vertx-core/src/test/java/io/vertx/tests/http/Http2Test.java b/vertx-core/src/test/java/io/vertx/tests/http/Http2Test.java index 24af4d5f18c..b587723f13d 100644 --- a/vertx-core/src/test/java/io/vertx/tests/http/Http2Test.java +++ b/vertx-core/src/test/java/io/vertx/tests/http/Http2Test.java @@ -722,6 +722,35 @@ public void testClearTextUpgradeConnectionConcurrency() throws Exception { assertTrue(((io.vertx.core.http.impl.UnpooledHttpClientConnection) conn).unwrap().concurrency() > 1); } + @Test + public void testClearTextUpgradeRejectedPoolGrowth() throws Exception { + // An HTTP/1.1 only server rejects the upgrade: the connection is reclassified and the pool + // dials more connections for the pending requests instead of staying capped by the HTTP/2 + // pool size + AtomicInteger connections = new AtomicInteger(); + List responses = Collections.synchronizedList(new ArrayList<>()); + server = vertx.createHttpServer(new HttpServerOptions().setHttp2ClearTextEnabled(false)); + server.connectionHandler(conn -> connections.incrementAndGet()); + server.requestHandler(req -> { + // Send the response head, defer the end: the request holds the connection while the + // upgrade resolves + HttpServerResponse resp = req.response().setChunked(true); + resp.write("x"); + responses.add(resp); + }); + startServer(testAddress); + client = vertx.createHttpClient(new HttpClientOptions().setProtocolVersion(HttpVersion.HTTP_2)); + Future body1 = client.request(new RequestOptions(requestOptions).setSsl(false)) + .compose(req -> req.send().compose(HttpClientResponse::body)); + Future body2 = client.request(new RequestOptions(requestOptions).setSsl(false)) + .compose(req -> req.send().compose(HttpClientResponse::body)); + AsyncTestBase.assertWaitUntil(() -> responses.size() == 2); + assertEquals(2, connections.get()); + new ArrayList<>(responses).forEach(HttpServerResponse::end); + body1.await(); + body2.await(); + } + @Test public void testClearTextUpgradeWithBody() throws Exception { server = vertx.createHttpServer().requestHandler(req -> {