From 6e3c1e1044154bcf87e34003583769ab4ed147ae Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Wed, 2 Dec 2026 10:09:26 +0100 Subject: [PATCH] Pool acquisition timeout Motivation: Every pool waiter should have a deadline: the ground for bounding the wait queue under persistent connect failures. RequestOptions #setConnectTimeout is the pool acquisition timeout; its -1 default used to disable it, leaving the waiter without a deadline. Being connected is relative to the layer connected to: for a pooled request it is obtaining a connection from the pool, so when the request leaves it unset, the connect timeout of the transport being connected to is the natural default. Changes: HttpClientImpl keeps the connect timeout of each transport, passed by the builder, and resolves the acquisition timeout against the version determined for the request when the request options leave it unset. A disabled transport connect timeout cannot provide the default: creating a pooled client with connectTimeout 0 is rejected. HttpConnectOptions documents the default and the distinction with the transport option. DefaultConnectionPool#acquire fails the acquisition with IllegalArgumentException when the timeout is null, zero or negative: the deadline is always set and the eviction guard on the unset deadline is dropped. The pool tests acquire with an oracle timeout. When the connect attempt itself is what times out, the inherited deadline expires with it and the acquisition reports the timeout: testConnectTimeout now expects TimeoutException instead of the Netty ConnectTimeoutException. The new PoolOptions refresh period (default 100 ms, must be positive) drives the periodic refresh performing the pool maintenance tasks and supersedes the deprecated pool cleaner period: the period bounds the resolution of the connect timeout. Assisted-by: Anthropic Claude (claude-fable-5) Co-Authored-By: Claude Fable 5 Signed-off-by: Julien Viet --- vertx-core/src/main/asciidoc/http.adoc | 2 +- .../vertx/core/http/PoolOptionsConverter.java | 8 + .../vertx/core/http/HttpConnectOptions.java | 9 +- .../java/io/vertx/core/http/PoolOptions.java | 46 +++++- .../http/impl/HttpClientBuilderInternal.java | 4 +- .../vertx/core/http/impl/HttpClientImpl.java | 38 ++++- .../internal/pool/DefaultConnectionPool.java | 7 +- .../java/io/vertx/tests/http/Http1xTest.java | 27 ++++ .../tests/http/HttpClientResolverTest.java | 4 +- .../java/io/vertx/tests/http/HttpTest.java | 17 +- .../vertx/tests/pool/ConnectionPoolTest.java | 147 +++++++++--------- .../tests/pool/DefaultConnectionPoolTest.java | 67 +++++--- .../java/io/vertx/tests/pool/StressTest.java | 5 +- 13 files changed, 257 insertions(+), 124 deletions(-) diff --git a/vertx-core/src/main/asciidoc/http.adoc b/vertx-core/src/main/asciidoc/http.adoc index 7ed94572078..5f836d807d0 100644 --- a/vertx-core/src/main/asciidoc/http.adoc +++ b/vertx-core/src/main/asciidoc/http.adoc @@ -1061,7 +1061,7 @@ You can configure various pool {@link io.vertx.core.http.PoolOptions options} as * {@link io.vertx.core.http.PoolOptions options#setHttp1MaxSize} the maximum number of opened per HTTP/1.x server (5 by default) * {@link io.vertx.core.http.PoolOptions options#setHttp2MaxSize} the maximum number of opened per HTTP/2 server (1 by default), you *should* not change this value since a single HTTP/2 connection is capable of delivering the same performance level than multiple HTTP/1.x connections * {@link io.vertx.core.http.PoolOptions options#setHttp3MaxSize} the maximum number of opened per HTTP/3 server (1 by default), you *should* not change this value since a single HTTP/3 connection is capable of delivering the same performance level than multiple HTTP/1.x connections -* {@link io.vertx.core.http.PoolOptions options#setCleanerPeriod} the period in milliseconds at which the pool checks expired connections (1 second by default) +* {@link io.vertx.core.http.PoolOptions options#setRefreshPeriod} the period at which the pool performs its maintenance tasks (100 milliseconds by default): expired connections are closed and expired connection acquisitions are timed out, the period bounds the resolution of the connect timeout * {@link io.vertx.core.http.PoolOptions options#setEventLoopSize} sets the number of event loops the pool use ** the default value `0` configures the pool to use the event loop of the caller ** a positive value configures the pool load balance the creation of connection over a list of event loops determined by the value diff --git a/vertx-core/src/main/generated/io/vertx/core/http/PoolOptionsConverter.java b/vertx-core/src/main/generated/io/vertx/core/http/PoolOptionsConverter.java index b4e7e2a014c..d2e1ba7d3f1 100644 --- a/vertx-core/src/main/generated/io/vertx/core/http/PoolOptionsConverter.java +++ b/vertx-core/src/main/generated/io/vertx/core/http/PoolOptionsConverter.java @@ -42,6 +42,11 @@ static void fromJson(Iterable> json, PoolOpt obj.setCleanerPeriod(((Number)member.getValue()).intValue()); } break; + case "refreshPeriod": + if (member.getValue() instanceof Number) { + obj.setRefreshPeriod(java.time.Duration.of(((Number)member.getValue()).longValue(), java.time.temporal.ChronoUnit.MILLIS)); + } + break; case "eventLoopSize": if (member.getValue() instanceof Number) { obj.setEventLoopSize(((Number)member.getValue()).intValue()); @@ -69,6 +74,9 @@ static void toJson(PoolOptions obj, java.util.Map json) { } json.put("maxLifetime", obj.getMaxLifetime()); json.put("cleanerPeriod", obj.getCleanerPeriod()); + if (obj.getRefreshPeriod() != null) { + json.put("refreshPeriod", obj.getRefreshPeriod().toMillis()); + } json.put("eventLoopSize", obj.getEventLoopSize()); json.put("maxWaitQueueSize", obj.getMaxWaitQueueSize()); } diff --git a/vertx-core/src/main/java/io/vertx/core/http/HttpConnectOptions.java b/vertx-core/src/main/java/io/vertx/core/http/HttpConnectOptions.java index d914d7aa5a0..fbc3ceeaa75 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/HttpConnectOptions.java +++ b/vertx-core/src/main/java/io/vertx/core/http/HttpConnectOptions.java @@ -275,9 +275,12 @@ public long getConnectTimeout() { * Sets the amount of time after which, if the request is not obtained from the client within the timeout period, * the {@code Future} obtained from the client is failed with a {@link java.util.concurrent.TimeoutException}. * - * Note this is not related to the TCP {@link HttpClientOptions#setConnectTimeout(int)} option, when a request is made against - * a pooled HTTP client, the timeout applies to the duration to obtain a connection from the pool to serve the request, the timeout - * might fire because the server does not respond in time or the pool is too busy to serve a request. + * Note this is distinct from the transport connect timeout ({@link HttpClientConfig#setConnectTimeout}), when a request is made + * against a pooled HTTP client, the timeout applies to the duration to obtain a connection from the pool to serve the request, the + * timeout might fire because the server does not respond in time or the pool is too busy to serve a request. + * + * When the timeout is not set, it defaults to the connect timeout of the transport being connected to, so that every + * request waits a bounded amount of time for a connection. * * @param timeout the amount of time in milliseconds. * @return a reference to this, so the API can be used fluently diff --git a/vertx-core/src/main/java/io/vertx/core/http/PoolOptions.java b/vertx-core/src/main/java/io/vertx/core/http/PoolOptions.java index 29560eb56f3..153a9e777e4 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/PoolOptions.java +++ b/vertx-core/src/main/java/io/vertx/core/http/PoolOptions.java @@ -15,6 +15,7 @@ import io.vertx.core.impl.Arguments; import io.vertx.core.json.JsonObject; +import java.time.Duration; import java.util.concurrent.TimeUnit; /** @@ -58,9 +59,17 @@ public class PoolOptions { /** * Default pool cleaner period = 1000 ms (1 second) + * + * @deprecated the pool cleaner period is unused, superseded by {@link #DEFAULT_REFRESH_PERIOD} */ + @Deprecated public static final int DEFAULT_POOL_CLEANER_PERIOD = 1000; + /** + * Default pool refresh period = 100 ms + */ + public static final Duration DEFAULT_REFRESH_PERIOD = Duration.ofMillis(100); + /** * Default pool event loop size = 0 (reuse current event-loop) */ @@ -72,6 +81,7 @@ public class PoolOptions { private int maxLifetime; private TimeUnit maxLifetimeUnit; private int cleanerPeriod; + private Duration refreshPeriod; private int eventLoopSize; private int maxWaitQueueSize; @@ -85,6 +95,7 @@ public PoolOptions() { maxLifetime = DEFAULT_MAXIMUM_LIFETIME; maxLifetimeUnit = DEFAULT_MAXIMUM_LIFETIME_TIME_UNIT; cleanerPeriod = DEFAULT_POOL_CLEANER_PERIOD; + refreshPeriod = DEFAULT_REFRESH_PERIOD; eventLoopSize = DEFAULT_POOL_EVENT_LOOP_SIZE; maxWaitQueueSize = DEFAULT_MAX_WAIT_QUEUE_SIZE; } @@ -101,6 +112,7 @@ public PoolOptions(PoolOptions other) { this.maxLifetime = other.maxLifetime; this.maxLifetimeUnit = other.maxLifetimeUnit; this.cleanerPeriod = other.cleanerPeriod; + this.refreshPeriod = other.refreshPeriod; this.eventLoopSize = other.eventLoopSize; this.maxWaitQueueSize = other.maxWaitQueueSize; } @@ -224,23 +236,53 @@ public PoolOptions setMaxLifetime(int maxLifetime) { /** * @return the connection pool cleaner period in ms. + * + * @deprecated the pool cleaner period is unused, superseded by {@link #getRefreshPeriod()} */ + @Deprecated public int getCleanerPeriod() { return cleanerPeriod; } /** - * Set the connection pool cleaner period in milli seconds, a non positive value disables expiration checks and connections - * will remain in the pool until they are closed. + * Set the connection pool cleaner period in milli seconds. * * @param cleanerPeriod the pool cleaner period * @return a reference to this, so the API can be used fluently + * + * @deprecated the pool cleaner period is unused, superseded by {@link #setRefreshPeriod(Duration)} */ + @Deprecated public PoolOptions setCleanerPeriod(int cleanerPeriod) { this.cleanerPeriod = cleanerPeriod; return this; } + /** + * @return the connection pool refresh period + */ + public Duration getRefreshPeriod() { + return refreshPeriod; + } + + /** + * Set the connection pool refresh period, the period must be positive. + *

+ * The pool is refreshed periodically to perform its maintenance tasks: connections that exceeded their keep alive + * timeout or maximum lifetime are closed and expired connection acquisitions are timed out. The refresh period + * bounds the resolution of the connect timeout. + * + * @param refreshPeriod the pool refresh period + * @return a reference to this, so the API can be used fluently + */ + public PoolOptions setRefreshPeriod(Duration refreshPeriod) { + if (refreshPeriod == null || refreshPeriod.isZero() || refreshPeriod.isNegative()) { + throw new IllegalArgumentException("refreshPeriod must be > 0"); + } + this.refreshPeriod = refreshPeriod; + return this; + } + /** * @return the max number of event-loop a pool will use, the default value is {@code 0} which implies * to reuse the current event-loop diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/HttpClientBuilderInternal.java b/vertx-core/src/main/java/io/vertx/core/http/impl/HttpClientBuilderInternal.java index 3fe0aa787ca..bbbc81de294 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/HttpClientBuilderInternal.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/HttpClientBuilderInternal.java @@ -227,7 +227,9 @@ public LegacyHttpClient( HttpClientOptions options) { super(vertx, resolver, redirectHandler, httpMetrics, poolOptions, defaultProxyOptions, nonProxyHosts, loadBalancer, followAlternativeServices, resolverKeepAlive, resolverMaxTtl, verifyHost, validateUri, defaultSsl, defaultHost, defaultPort, - maxRedirects, maxRedirectBufferSize, versions, sslOptions, connectHandler, tcpTransport, quicTransport); + maxRedirects, maxRedirectBufferSize, versions, sslOptions, connectHandler, tcpTransport, quicTransport, + config.getTcpConfig().getConnectTimeout() != null ? config.getTcpConfig().getConnectTimeout().toMillis() : 0L, + config.getQuicConfig().getConnectTimeout() != null ? config.getQuicConfig().getConnectTimeout().toMillis() : 0L); this.config = config; this.options = options; } diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/HttpClientImpl.java b/vertx-core/src/main/java/io/vertx/core/http/impl/HttpClientImpl.java index 1da1debda45..325b6c0650a 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/HttpClientImpl.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/HttpClientImpl.java @@ -57,11 +57,14 @@ public class HttpClientImpl extends HttpClientBase implements HttpClientInternal private final ResourceManager resourceManager; private final Function> redirectHandler; private long timerID; + private final long refreshPeriod; private final Function contextProvider; private final long maxLifetime; private final HttpClientTransport tcpTransport; private final HttpClientTransport quicTransport; private final HttpClientTransport defaultTransport; + private final long tcpConnectTimeout; + private final long quicConnectTimeout; private final EndpointResolverInternal resolver; private final OriginResolver originEndpoints; private final EndpointResolverInternal originResolver; @@ -100,7 +103,9 @@ public class HttpClientImpl extends HttpClientBase implements HttpClientInternal ClientSSLOptions sslOptions, Handler connectHandler, HttpClientTransport tcpTransport, - HttpClientTransport quicTransport) { + HttpClientTransport quicTransport, + long tcpConnectTimeout, + long quicConnectTimeout) { super(vertx, httpMetrics, defaultProxyOptions, nonProxyHosts); if (sslOptions != null) { @@ -109,8 +114,16 @@ public class HttpClientImpl extends HttpClientBase implements HttpClientInternal boolean resolveAll = loadBalancer != null; + if (tcpTransport != null && tcpConnectTimeout <= 0L) { + throw new IllegalArgumentException("The connect timeout must be positive: it is the default acquisition timeout of the pool"); + } + if (quicTransport != null && quicConnectTimeout <= 0L) { + throw new IllegalArgumentException("The connect timeout must be positive: it is the default acquisition timeout of the pool"); + } this.tcpTransport = tcpTransport; this.quicTransport = quicTransport; + this.tcpConnectTimeout = tcpConnectTimeout; + this.quicConnectTimeout = quicConnectTimeout; this.defaultTransport = tcpTransport != null ? tcpTransport : quicTransport; this.originEndpoints = new OriginResolver<>(vertx, resolveAll, this); this.resolver = (EndpointResolverInternal) resolver; @@ -145,11 +158,14 @@ public class HttpClientImpl extends HttpClientBase implements HttpClientInternal this.contextProvider = ConnectionPool.EVENT_LOOP_CONTEXT_PROVIDER; } - // Init time - if (poolOptions.getCleanerPeriod() > 0) { + // The periodic refresh performs all the pool maintenance tasks: it reaps the expired connections + // and times out the expired connection waiters + Duration refreshPeriod = poolOptions.getRefreshPeriod(); + this.refreshPeriod = refreshPeriod != null ? refreshPeriod.toMillis() : 0; + if (this.refreshPeriod > 0) { PoolChecker checker = new PoolChecker(this); ContextInternal timerContext = vertx.createEventLoopContext(); - timerID = timerContext.setTimer(poolOptions.getCleanerPeriod(), checker); + timerID = timerContext.setTimer(this.refreshPeriod, checker); } } @@ -184,7 +200,7 @@ public EndpointResolverInternal resolver() { protected void checkExpired(Handler checker) { synchronized (this) { if (!closeSequence.started()) { - timerID = vertx.setTimer(poolOptions.getCleanerPeriod(), checker); + timerID = vertx.setTimer(refreshPeriod, checker); } } originResolver.checkExpired(); @@ -457,6 +473,14 @@ private HttpClientTransport transport(HttpVersion version) { return version == HttpVersion.HTTP_3 ? quicTransport : tcpTransport; } + private long connectTimeout(HttpVersion version, long timeout) { + if (timeout <= 0L) { + HttpClientTransport transport = version != null ? transport(version) : defaultTransport; + timeout = transport instanceof TcpHttpClientTransport ? tcpConnectTimeout : quicConnectTimeout; + } + return timeout; + } + private Future acquireConnection(RequestOptions request, ContextInternal ctx) { HttpVersion version = request.getProtocolVersion(); if (version != null && !versions.contains(version)) { @@ -476,7 +500,7 @@ private Future acquireConnection(RequestOptions request, Cont (SocketAddress) connectionRequest.server, connectionRequest.authority, connectionRequest.proxyOptions, - group -> connectionRequest.acquire(group.requestConnection(connectionRequest.ctx, connectionRequest.connectTimeout), null, null)); + group -> connectionRequest.acquire(group.requestConnection(connectionRequest.ctx, connectTimeout(connectionRequest.version, connectionRequest.connectTimeout)), null, null)); } else { PromiseInternal promise = vertx.promise(); connectionRequest.endpointResolver.lookupEndpoint(connectionRequest.address, promise); @@ -496,7 +520,7 @@ private Future acquireConnection(RequestOptions request, Cont serverAddress, authority, null, - group -> connectionRequest.acquire(group.requestConnection(connectionRequest.ctx, connectionRequest.connectTimeout), selection.server, selection.alternative)); + group -> connectionRequest.acquire(group.requestConnection(connectionRequest.ctx, connectTimeout(selectedVersion, connectionRequest.connectTimeout)), selection.server, selection.alternative)); }); } } 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 edbe332dc5e..8262143c97c 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 @@ -449,7 +449,7 @@ private void progress(TaskList tasks) { while (current != null) { PoolWaiter waiter = current; current = waiters.next(current); - if (waiter.deadlineNanos != 0 && roundNanos - waiter.deadlineNanos >= 0) { + if (roundNanos - waiter.deadlineNanos >= 0) { waiters.remove(waiter); boolean dequeued = waiter.queued; Task task = new Task() { @@ -943,6 +943,11 @@ public void acquire(ContextInternal context, int kind, Duration timeout, Complet @Override public void acquire(ContextInternal context, PoolWaiter.Listener listener, int kind, Duration timeout, Completable> handler) { + if (timeout == null || timeout.isZero() || timeout.isNegative()) { + Future> fut = context.failedFuture(new IllegalArgumentException("A positive acquire timeout is required: every pool waiter has a deadline")); + fut.onComplete(handler); + return; + } execute(new Acquire<>(context, listener, capacityFactors[kind], timeout, handler)); } diff --git a/vertx-core/src/test/java/io/vertx/tests/http/Http1xTest.java b/vertx-core/src/test/java/io/vertx/tests/http/Http1xTest.java index 4b71abeb93b..4b6e57e5ac9 100644 --- a/vertx-core/src/test/java/io/vertx/tests/http/Http1xTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/http/Http1xTest.java @@ -6353,4 +6353,31 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception tracking.future().await(); return request; } + + @Test + public void testDisabledConnectTimeoutRejected() { + // A disabled transport connect timeout cannot default the pool acquisition timeout: the + // pooled client creation fails + assertThatThrownBy(() -> vertx.createHttpClient(new HttpClientOptions().setConnectTimeout(0))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void testConnectTimeoutDefaultsToTransportConnectTimeout() throws Exception { + server.requestHandler(req -> { + // Hold the connection: the next request waits + }); + startServer(testAddress); + client = vertx.createHttpClient(new HttpClientOptions().setConnectTimeout(200), new PoolOptions().setHttp1MaxSize(1)); + client.request(new RequestOptions(requestOptions)).compose(HttpClientRequest::send); + // A request without connect timeout gets the transport connect timeout as acquisition + // deadline + long begin = System.currentTimeMillis(); + assertThat(client.request(new RequestOptions(requestOptions))) + .isFailure() + .asInstanceOf(java.util.concurrent.TimeoutException.class) + .compose(cause -> System.currentTimeMillis() - begin >= 200 ? Future.succeededFuture() + : Future.failedFuture(new AssertionError("The acquisition failed before the default timeout"))) + .await(); + } } diff --git a/vertx-core/src/test/java/io/vertx/tests/http/HttpClientResolverTest.java b/vertx-core/src/test/java/io/vertx/tests/http/HttpClientResolverTest.java index 39be2f60c1f..93d4026918e 100644 --- a/vertx-core/src/test/java/io/vertx/tests/http/HttpClientResolverTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/http/HttpClientResolverTest.java @@ -132,7 +132,7 @@ public void testKeepAliveTimeout(Vertx vertx) { .await(); HttpClientConfig clientConfig = new HttpClientConfig().setResolverConfig(new ClientResolverConfig().setKeepAliveTimeout(Duration.ofMillis(50))); - HttpClient client = vertx.createHttpClient(clientConfig, new PoolOptions().setCleanerPeriod(50)); + HttpClient client = vertx.createHttpClient(clientConfig, new PoolOptions().setRefreshPeriod(Duration.ofMillis(50))); // Create a connection to the server first (warm-up) before // we test the origin resolver @@ -187,7 +187,7 @@ public void testMaxKeepAlive() throws Exception { .await(); HttpClientConfig clientConfig = new HttpClientConfig().setResolverConfig(new ClientResolverConfig().setMaxKeepAlive(Duration.ofMillis(500))); - HttpClient client = vertx.createHttpClient(clientConfig, new PoolOptions().setCleanerPeriod(10)); + HttpClient client = vertx.createHttpClient(clientConfig, new PoolOptions().setRefreshPeriod(Duration.ofMillis(10))); long now = System.currentTimeMillis(); while (true) { assertTrue((System.currentTimeMillis() - now) < 20_000); 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 7619e1007c1..922c0d79457 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 @@ -12,7 +12,6 @@ package io.vertx.tests.http; import io.netty.buffer.ByteBufUtil; -import io.netty.channel.ConnectTimeoutException; import io.netty.channel.EventLoop; import io.netty.handler.codec.compression.DecompressionException; import io.netty.handler.codec.http.HttpHeaderNames; @@ -5200,7 +5199,7 @@ public void testKeepAliveTimeout(Checkpoint checkpoint) throws Exception { protected void testKeepAliveTimeout(Checkpoint checkpoint, HttpClientConfigurator options, PoolOptions poolOptions, int numReqs) throws Exception { startServer(testAddress); - client = options.create(vertx, poolOptions.setCleanerPeriod(1)); + client = options.create(vertx, poolOptions.setRefreshPeriod(Duration.ofMillis(1))); AtomicInteger respCount = new AtomicInteger(); List> futures = new ArrayList<>(); for (int i = 0;i < numReqs;i++) { @@ -5230,12 +5229,12 @@ protected void testKeepAliveTimeout(Checkpoint checkpoint, HttpClientConfigurato @Test public void testPoolNotExpiring1(Checkpoint checkpoint) throws Exception { - testPoolNotExpiring(checkpoint, config.forClient().setKeepAliveTimeout(Duration.ofSeconds(100)), new PoolOptions().setCleanerPeriod(0)); + testPoolNotExpiring(checkpoint, config.forClient().setKeepAliveTimeout(Duration.ofSeconds(100)), new PoolOptions()); } @Test public void testPoolNotExpiring2(Checkpoint checkpoint) throws Exception { - testPoolNotExpiring(checkpoint, config.forClient().setKeepAliveTimeout(Duration.ofSeconds(0)), new PoolOptions().setCleanerPeriod(10)); + testPoolNotExpiring(checkpoint, config.forClient().setKeepAliveTimeout(Duration.ofSeconds(0)), new PoolOptions().setRefreshPeriod(Duration.ofMillis(10))); } private void testPoolNotExpiring(Checkpoint checkpoint, HttpClientConfigurator options, PoolOptions poolOptions) throws Exception { @@ -5268,7 +5267,7 @@ private void testPoolNotExpiring(Checkpoint checkpoint, HttpClientConfigurator o @Test public void testMaxLifetime(Checkpoint checkpoint) throws Exception { - int poolCleanerPeriod = 100; + int poolRefreshPeriod = 100; int maxLifetime = 3000; server .connectionHandler(conn -> { @@ -5276,9 +5275,9 @@ public void testMaxLifetime(Checkpoint checkpoint) throws Exception { conn.closeHandler(v -> { long lifetime = System.currentTimeMillis() - now; int delta = 500; - int lowerBound = maxLifetime - poolCleanerPeriod - delta; + int lowerBound = maxLifetime - poolRefreshPeriod - delta; assertTrue("Was expecting connection to be closed in more than " + lowerBound + ": " + lifetime, lifetime >= lowerBound); - int upperBound = maxLifetime + poolCleanerPeriod + delta; + int upperBound = maxLifetime + poolRefreshPeriod + delta; assertTrue("Was expecting connection to be closed in less than " + upperBound + ": " + lifetime, lifetime <= upperBound); checkpoint.succeed(); }); @@ -5289,7 +5288,7 @@ public void testMaxLifetime(Checkpoint checkpoint) throws Exception { startServer(testAddress); PoolOptions poolOptions = new PoolOptions() - .setCleanerPeriod(poolCleanerPeriod) + .setRefreshPeriod(Duration.ofMillis(poolRefreshPeriod)) .setMaxLifetime(maxLifetime) .setMaxLifetimeUnit(TimeUnit.MILLISECONDS); client = createHttpClient(poolOptions); @@ -6753,7 +6752,7 @@ public void testConnectTimeout() { client .request(new RequestOptions().setHost(TestUtils.NON_ROUTABLE_HOST).setPort(config.port())) .await(); - }).isInstanceOf(ConnectTimeoutException.class); + }).isInstanceOf(TimeoutException.class); } @Test 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 b1f10de2141..b4ec9f486b4 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 @@ -10,6 +10,7 @@ */ package io.vertx.tests.pool; +import java.time.Duration; import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.Vertx; @@ -36,6 +37,8 @@ public class ConnectionPoolTest extends VertxTestBase { + static final Duration TIMEOUT = Duration.ofMinutes(10); + VertxInternal vertx; public ConnectionPoolTest() { @@ -63,7 +66,7 @@ public void testConnect() { ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); Connection expected = new Connection(); pool - .acquire(context, 0, TestUtils.onSuccess2(lease -> { + .acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(expected, lease.get()); Assert.assertEquals(0, pool.requests()); testComplete(); @@ -83,7 +86,7 @@ public void testAcquireRecycledConnection() throws Exception { Connection expected = new Connection(); CountDownLatch latch = new CountDownLatch(1); pool - .acquire(context, 0, TestUtils.onSuccess2(lease -> { + .acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { lease.recycle(); latch.countDown(); })); @@ -91,7 +94,7 @@ public void testAcquireRecycledConnection() throws Exception { Assert.assertSame(context.nettyEventLoop(), request.context.nettyEventLoop()); request.connect(expected, 0); TestUtils.awaitLatch(latch); - pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(expected, lease.get()); testComplete(); })); @@ -104,7 +107,7 @@ public void testRecycleRemovedConnection() throws Exception { ConnectionManager mgr = new ConnectionManager(); ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); Connection expected1 = new Connection(); - Future> fut = Future.future(p -> pool.acquire(context, 0, p)); + Future> fut = Future.future(p -> pool.acquire(context, 0, TIMEOUT, p)); ConnectionRequest request1 = mgr.assertRequest(); request1.connect(expected1, 0); CountDownLatch latch = new CountDownLatch(1); @@ -115,7 +118,7 @@ public void testRecycleRemovedConnection() throws Exception { })); TestUtils.awaitLatch(latch); Connection expected2 = new Connection(); - pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(expected2, lease.get()); testComplete(); })); @@ -132,13 +135,13 @@ public void testConcurrency() throws Exception { Connection expected = new Connection(); CountDownLatch latch = new CountDownLatch(1); pool - .acquire(context, 0, TestUtils.onSuccess2(conn -> { + .acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(conn -> { latch.countDown(); })); ConnectionRequest request = mgr.assertRequest(); request.concurrency(2).connect(expected, 0); TestUtils.awaitLatch(latch); - pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(lease.get(), expected); testComplete(); })); @@ -152,14 +155,14 @@ public void testIncreaseConcurrency() throws Exception { ContextInternal ctx = vertx.createEventLoopContext(); Connection conn1 = new Connection(); CountDownLatch l1 = new CountDownLatch(1); - pool.acquire(ctx, 0, TestUtils.onSuccess2(lease -> l1.countDown())); + pool.acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(lease -> l1.countDown())); CountDownLatch l2 = new CountDownLatch(1); pool - .acquire(ctx, 0, TestUtils.onSuccess2(lease -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { l2.countDown(); })); CountDownLatch l3 = new CountDownLatch(1); - pool.acquire(ctx, 0, TestUtils.onSuccess2(lease -> l3.countDown())); + pool.acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(lease -> l3.countDown())); ConnectionRequest request = mgr.assertRequest(); request.connect(conn1, 0); TestUtils.awaitLatch(l1); @@ -178,12 +181,12 @@ public void testSatisfyPendingWaitersWithExtraConcurrency() throws Exception { Connection expected = new Connection(); AtomicInteger seq = new AtomicInteger(); pool - .acquire(context, 0, TestUtils.onSuccess2(lease -> { + .acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(lease.get(), expected); Assert.assertEquals(0, seq.getAndIncrement()); })); pool - .acquire(context, 0, TestUtils.onSuccess2(lease -> { + .acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(lease.get(), expected); Assert.assertEquals(1, seq.getAndIncrement()); testComplete(); @@ -201,12 +204,12 @@ public void testEmptyConcurrency() { Connection expected = new Connection(); AtomicInteger seq = new AtomicInteger(); pool - .acquire(context, 0, TestUtils.onSuccess2(lease -> { + .acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(lease.get(), expected); Assert.assertEquals(1, seq.getAndIncrement()); })); pool - .acquire(context, 0, TestUtils.onSuccess2(lease -> { + .acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(lease.get(), expected); Assert.assertEquals(2, seq.getAndIncrement()); testComplete(); @@ -228,7 +231,7 @@ public void testEmptyConcurrencyWithManyWaiters() { for (int i = 0;i < 3;i++) { int expectedSeq = i + 1; pool - .acquire(context, 0, TestUtils.onSuccess2(lease -> { + .acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(lease.get(), expected); Assert.assertEquals(expectedSeq, seq.getAndIncrement()); if (expectedSeq == 3) { @@ -253,17 +256,17 @@ public void testDecreaseConcurrency() throws Exception { CountDownLatch l2 = new CountDownLatch(1); Lease[] leases = new Lease[3]; pool - .acquire(ctx, 0, TestUtils.onSuccess2(lease -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { leases[0] = lease; l1.countDown(); })); pool - .acquire(ctx, 0, TestUtils.onSuccess2(lease -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { leases[1] = lease; l1.countDown(); })); pool - .acquire(ctx, 0, TestUtils.onSuccess2(lease -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { leases[2] = lease; l2.countDown(); })); @@ -289,14 +292,14 @@ public void testWaiter() throws Exception { ConnectionPool pool = pool(mgr, new int[] { 1 }); Connection expected = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); - pool.acquire(ctx1, 0, TestUtils.onSuccess2(latch::complete)); + pool.acquire(ctx1, 0, TIMEOUT, TestUtils.onSuccess2(latch::complete)); ConnectionRequest request = mgr.assertRequest(); request.connect(expected, 0); Lease lease1 = latch.get(10, TimeUnit.SECONDS); AtomicBoolean recycled = new AtomicBoolean(); ContextInternal ctx2 = vertx.createEventLoopContext(); pool - .acquire(ctx2, 0, TestUtils.onSuccess2(lease2 -> { + .acquire(ctx2, 0, TIMEOUT, TestUtils.onSuccess2(lease2 -> { Assert.assertSame(ctx1.nettyEventLoop(), ((ContextInternal) Vertx.currentContext()).nettyEventLoop()); Assert.assertTrue(recycled.get()); testComplete(); @@ -314,7 +317,7 @@ public void testRemoveSingleConnection() throws Exception { ConnectionPool pool = pool(mgr, new int[] { 1 }, 1); Connection conn = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); - pool.acquire(ctx1, 0, TestUtils.onSuccess2(latch::complete)); + pool.acquire(ctx1, 0, TIMEOUT, TestUtils.onSuccess2(latch::complete)); ConnectionRequest request = mgr.assertRequest(); request.connect(conn, 0); latch.get(10, TimeUnit.SECONDS); @@ -330,10 +333,10 @@ public void testRemoveFirstConnection() throws Exception { ConnectionPool pool = pool(mgr, new int[] { 2 }, 2); Connection conn1 = new Connection(); CompletableFuture> latch1 = new CompletableFuture<>(); - pool.acquire(ctx, 0, TestUtils.onSuccess2(latch1::complete)); + pool.acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(latch1::complete)); Connection conn2 = new Connection(); CompletableFuture> latch2 = new CompletableFuture<>(); - pool.acquire(ctx, 0, TestUtils.onSuccess2(latch2::complete)); + pool.acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(latch2::complete)); ConnectionRequest request1 = mgr.assertRequest(); request1.connect(conn1, 0); ConnectionRequest request2 = mgr.assertRequest(); @@ -352,7 +355,7 @@ public void testRemoveSingleConnectionWithWaiter() throws Exception { Connection connection1 = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); pool - .acquire(ctx1, 0, TestUtils.onSuccess2(latch::complete)); + .acquire(ctx1, 0, TIMEOUT, TestUtils.onSuccess2(latch::complete)); ConnectionRequest request1 = mgr.assertRequest(); request1.connect(connection1, 0); Lease lease1 = latch.get(10, TimeUnit.SECONDS); @@ -361,7 +364,7 @@ public void testRemoveSingleConnectionWithWaiter() throws Exception { Connection conn2 = new Connection(); ContextInternal ctx2 = vertx.createEventLoopContext(); pool - .acquire(ctx2, 0, TestUtils.onSuccess2(lease2 -> { + .acquire(ctx2, 0, TIMEOUT, TestUtils.onSuccess2(lease2 -> { Assert.assertSame(ctx2.nettyEventLoop(), ((ContextInternal) Vertx.currentContext()).nettyEventLoop()); Assert.assertTrue(evicted.get()); Assert.assertSame(conn2, lease2.get()); @@ -384,13 +387,13 @@ public void testConnectFailureWithPendingWaiter() throws Exception { CountDownLatch latch = new CountDownLatch(1); ContextInternal ctx1 = vertx.createEventLoopContext(); pool - .acquire(ctx1, 0, TestUtils.onFailure2(cause -> { + .acquire(ctx1, 0, TIMEOUT, TestUtils.onFailure2(cause -> { Assert.assertSame(failure, cause); Assert.assertEquals(1, pool.requests()); latch.countDown(); })); ContextInternal ctx2 = vertx.createEventLoopContext(); - pool.acquire(ctx2, 1, TestUtils.onSuccess2(lease -> { + pool.acquire(ctx2, 1, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(expected, lease.get()); testComplete(); })); @@ -439,7 +442,7 @@ private List testExpire(int num, int max, int... recycled) throws Excep for (int i = 0;i < num;i++) { Connection expected = new Connection(); pool - .acquire(ctx, 0, TestUtils.onSuccess2(lease -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(expected, lease.get()); leases.add(lease); latch.countDown(); @@ -474,7 +477,7 @@ public void testRemoveEvicted() throws Exception { ContextInternal ctx = vertx.createEventLoopContext(); CountDownLatch latch1 = new CountDownLatch(1); pool - .acquire(ctx, 0, TestUtils.onSuccess2(lease -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { lease.recycle(); latch1.countDown(); })); @@ -498,7 +501,7 @@ public void testSynchronousEviction() throws Exception { CountDownLatch latch2 = new CountDownLatch(1); CountDownLatch latch3 = new CountDownLatch(1); pool - .acquire(ctx, 0, TestUtils.onSuccess2(lease -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { lease.recycle(); latch1.countDown(); })); @@ -510,7 +513,7 @@ public void testSynchronousEviction() throws Exception { pool.evict(candidate -> { Assert.assertSame(candidate, conn1); pool - .acquire(ctx, 0, TestUtils.onSuccess2(lease -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Connection c2 = lease.get(); Assert.assertSame(conn2, c2); latch3.countDown(); @@ -530,7 +533,7 @@ public void testConnectionInProgressShouldNotBeEvicted() { ConnectionManager mgr = new ConnectionManager(); ConnectionPool pool = pool(mgr, new int[] { 1 }, 5); ContextInternal ctx = vertx.createEventLoopContext(); - pool.acquire(ctx, 0, (res, err) -> {}); + pool.acquire(ctx, 0, TIMEOUT, (res, err) -> {}); mgr.assertRequest(); pool .evict(c -> { @@ -547,7 +550,7 @@ public void testRecycleRemoveConnection() throws Exception { Connection expected = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); ContextInternal ctx1 = vertx.createEventLoopContext(); - pool.acquire(ctx1, 0, TestUtils.onSuccess2(latch::complete)); + pool.acquire(ctx1, 0, TIMEOUT, TestUtils.onSuccess2(latch::complete)); ConnectionRequest request = mgr.assertRequest(); request.connect(expected, 0); Lease lease = latch.get(); @@ -564,7 +567,7 @@ public void testRecycleMultiple() throws Exception { Connection expected = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); ContextInternal ctx1 = vertx.createEventLoopContext(); - pool.acquire(ctx1, 0, TestUtils.onSuccess2(latch::complete)); + pool.acquire(ctx1, 0, TIMEOUT, TestUtils.onSuccess2(latch::complete)); ConnectionRequest request = mgr.assertRequest(); request.connect(expected, 0); Lease lease = latch.get(); @@ -583,10 +586,10 @@ public void testMaxWaiters() { ContextInternal ctx = vertx.createEventLoopContext(); for (int i = 0;i < (5);i++) { pool - .acquire(ctx, 0, (res, err) -> Assert.fail()); + .acquire(ctx, 0, TIMEOUT, (res, err) -> Assert.fail()); } pool - .acquire(ctx, 0, TestUtils.onFailure2(err -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onFailure2(err -> { Assert.assertTrue(err instanceof ConnectionPoolTooBusyException); testComplete(); })); @@ -600,14 +603,14 @@ public void testHeterogeneousSizes() throws Exception { 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())); + pool.acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(lease -> latch.countDown())); Connection conn = new Connection(); mgr.assertRequest().connect(conn, 0); } TestUtils.awaitLatch(latch); Assert.assertEquals(10, pool.capacity()); pool - .acquire(ctx, 1, TestUtils.onSuccess2(lease -> { + .acquire(ctx, 1, TIMEOUT, TestUtils.onSuccess2(lease -> { })); Assert.assertEquals(1, pool.waiters()); @@ -622,7 +625,7 @@ public void testCapacityOvershoot() throws Exception { 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())); + pool.acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(lease -> latch.countDown())); } // The back-end establishes connections of the heavier kind: the pool temporarily exceeds // its maximum capacity, this is accepted @@ -633,7 +636,7 @@ public void testCapacityOvershoot() throws Exception { 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 -> { + pool.acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { })); Assert.assertEquals(1, pool.waiters()); Assert.assertEquals(0, pool.requests()); @@ -646,11 +649,11 @@ public void testClose() throws Exception { ContextInternal ctx = vertx.createEventLoopContext(); Connection conn1 = new Connection(); pool - .acquire(ctx, 0, TestUtils.onSuccess2(lease -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { })); waitFor(3); - pool.acquire(ctx, 0, TestUtils.onFailure2(err -> complete())); - pool.acquire(ctx, 0, TestUtils.onFailure2(err -> complete())); + pool.acquire(ctx, 0, TIMEOUT, TestUtils.onFailure2(err -> complete())); + pool.acquire(ctx, 0, TIMEOUT, TestUtils.onFailure2(err -> complete())); mgr.assertRequest().connect(conn1, 0); mgr.assertRequest(); pool @@ -697,7 +700,7 @@ public void onConnect(PoolWaiter waiter) { public void onEnqueue(PoolWaiter waiter) { waiterFut.complete(waiter); } - }, 0, (res, err) -> {}); + }, 0, TIMEOUT, (res, err) -> {}); PoolWaiter waiter = waiterFut.get(20, TimeUnit.SECONDS); ConnectionRequest request = mgr.assertRequest(); CountDownLatch latch = new CountDownLatch(1); @@ -707,7 +710,7 @@ public void onEnqueue(PoolWaiter waiter) { })); TestUtils.awaitLatch(latch); pool.evict(c -> true, TestUtils.onFailure2(err -> complete())); - pool.acquire(ctx, 0, TestUtils.onFailure2(err -> complete())); + pool.acquire(ctx, 0, TIMEOUT, TestUtils.onFailure2(err -> complete())); pool.cancel(waiter, TestUtils.onFailure2(err -> complete())); request.connect(new Connection(), 0); await(); @@ -718,7 +721,7 @@ public void testAcquireClosedConnection() throws Exception { ConnectionManager mgr = new ConnectionManager(); ConnectionPool pool = pool(mgr, new int[] { 1 }); ContextInternal context = vertx.createEventLoopContext(); - pool.acquire(context, 0, TestUtils.onSuccess2(Lease::recycle)); + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(Lease::recycle)); Connection expected = new Connection(); ConnectionRequest request = mgr.assertRequest(); request.connect(expected, 0); @@ -742,7 +745,7 @@ public void testAcquireClosedConnection() throws Exception { TestUtils.awaitLatch(latch1); AtomicBoolean closed = new AtomicBoolean(); pool - .acquire(context, 0, TestUtils.onSuccess2(lease -> { + .acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { // Get not null closed connection Assert.assertNotNull(lease.get()); Assert.assertTrue(closed.get()); @@ -770,7 +773,7 @@ private void testConnectResultAfterClose(boolean success) { ContextInternal ctx = vertx.createEventLoopContext(); AtomicInteger acquired = new AtomicInteger(); pool - .acquire(ctx, 0, (res, err) -> { + .acquire(ctx, 0, TIMEOUT, (res, err) -> { Assert.assertEquals(0, acquired.getAndIncrement()); }); Assert.assertEquals(1, pool.size()); @@ -804,14 +807,14 @@ public void testCancelQueuedWaiters() throws Exception { ConnectionPool pool = pool(mgr, new int[] { 1 }); CompletableFuture> w = new CompletableFuture<>(); pool - .acquire(context, 0, TestUtils.onSuccess2(lease -> { + .acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { })); pool.acquire(context, new PoolWaiter.Listener<>() { @Override public void onEnqueue(PoolWaiter waiter) { w.complete(waiter); } - }, 0, (res, err) -> Assert.fail()); + }, 0, TIMEOUT, (res, err) -> Assert.fail()); PoolWaiter waiter = w.get(10, TimeUnit.SECONDS); pool .cancel(waiter, TestUtils.onSuccess2(removed1 -> { @@ -860,7 +863,7 @@ public void onConnect(PoolWaiter waiter) { public void onEnqueue(PoolWaiter waiter) { waiterLatch.complete(waiter); } - }, 0, (res, err) -> Assert.fail()); + }, 0, TIMEOUT, (res, err) -> Assert.fail()); waiterLatch.get(10, TimeUnit.SECONDS); CountDownLatch enqueuedLatch = new CountDownLatch(extra); CountDownLatch recycledLatch = new CountDownLatch(extra); @@ -870,7 +873,7 @@ public void onEnqueue(PoolWaiter waiter) { public void onEnqueue(PoolWaiter waiter) { enqueuedLatch.countDown(); } - }, 0, TestUtils.onSuccess2(conn -> { + }, 0, TIMEOUT, TestUtils.onSuccess2(conn -> { conn.recycle(); recycledLatch.countDown(); })); @@ -894,7 +897,7 @@ public void onEnqueue(PoolWaiter waiter) { CountDownLatch doneLatch = new CountDownLatch(extra); for (int i = 0;i < extra;i++) { pool - .acquire(context, 0, TestUtils.onSuccess2(conn -> { + .acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(conn -> { doneLatch.countDown(); conn.recycle(); })); @@ -928,7 +931,7 @@ public void onConnect(PoolWaiter waiter) { public void onEnqueue(PoolWaiter waiter) { w.complete(waiter); } - }, 0, (res, err) -> { + }, 0, TIMEOUT, (res, err) -> { latch.countDown(); }); w.get(10, TimeUnit.SECONDS); @@ -957,7 +960,7 @@ public void testCancelWaiterDispatchedByRecycle() throws Exception { // Step 1: Acquire and establish a connection CountDownLatch connectedLatch = new CountDownLatch(1); AtomicReference> leaseRef = new AtomicReference<>(); - pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { leaseRef.set(lease); connectedLatch.countDown(); })); @@ -971,7 +974,7 @@ public void testCancelWaiterDispatchedByRecycle() throws Exception { public void onEnqueue(PoolWaiter waiter) { waiterFut.complete(waiter); } - }, 0, (res, err) -> { + }, 0, TIMEOUT, (res, err) -> { }); PoolWaiter waiter = waiterFut.get(10, TimeUnit.SECONDS); Assert.assertEquals(1, pool.waiters()); @@ -995,7 +998,7 @@ public void testConnectionSelector() throws Exception { ConnectionPool pool = pool(mgr, new int[] { 2 }); CountDownLatch latch1 = new CountDownLatch(1); pool - .acquire(context, 0, TestUtils.onSuccess2(lease -> { + .acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { lease.recycle(); latch1.countDown(); })); @@ -1013,7 +1016,7 @@ public void testConnectionSelector() throws Exception { return pooled; }); pool - .acquire(context, 0, TestUtils.onSuccess2(lease -> { + .acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { testComplete(); })); await(); @@ -1026,7 +1029,7 @@ public void testDefaultSelector() throws Exception { ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); CountDownLatch latch1 = new CountDownLatch(1); pool - .acquire(context1, 0, TestUtils.onSuccess2(lease -> { + .acquire(context1, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { lease.recycle(); latch1.countDown(); })); @@ -1037,7 +1040,7 @@ public void testDefaultSelector() throws Exception { TestUtils.awaitLatch(latch1); CountDownLatch latch2 = new CountDownLatch(1); pool - .acquire(context1, 0, TestUtils.onSuccess2(lease -> { + .acquire(context1, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertEquals(expected, lease.get()); lease.recycle(); latch2.countDown(); @@ -1051,7 +1054,7 @@ public void testDefaultSelector() throws Exception { .withClassLoader(context1.classLoader()) .build(); pool - .acquire(context2, 0, TestUtils.onSuccess2(lease -> { + .acquire(context2, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertEquals(expected, lease.get()); lease.recycle(); latch3.countDown(); @@ -1065,7 +1068,7 @@ public void testDefaultContextProviderUnwrap() { ConnectionManager mgr = new ConnectionManager(); ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); pool - .acquire(context.duplicate(), 0, TestUtils.onSuccess2(lease -> { + .acquire(context.duplicate(), 0, TIMEOUT, TestUtils.onSuccess2(lease -> { })); Assert.assertEquals(1, pool.requests()); ConnectionRequest request = mgr.assertRequest(); @@ -1078,7 +1081,7 @@ public void testDefaultContextProviderReusesSameEventLoop() { ConnectionManager mgr = new ConnectionManager(); ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); pool - .acquire(context.duplicate(), 0, TestUtils.onSuccess2(lease -> { + .acquire(context.duplicate(), 0, TIMEOUT, TestUtils.onSuccess2(lease -> { })); Assert.assertEquals(1, pool.requests()); ConnectionRequest request = mgr.assertRequest(); @@ -1107,7 +1110,7 @@ public Future> connect(ContextInternal context, Listen int num = seq.getAndIncrement(); ref .get() - .acquire(ctx, 0, TestUtils.onFailure2(err -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onFailure2(err -> { res.add(num); latch.countDown(); })); @@ -1128,7 +1131,7 @@ public boolean isValid(Connection connection) { ctx.runOnContext(v -> { int num = seq.getAndIncrement(); pool - .acquire(ctx, 0, TestUtils.onFailure2(err -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onFailure2(err -> { res.add(num); latch.countDown(); })); @@ -1157,13 +1160,13 @@ public Future> connect(ContextInternal context, Listen if (val == 0) { ref1 .get() - .acquire(ctx, 0, TestUtils.onFailure2(err -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onFailure2(err -> { res.add(1); latch.countDown(); })); ref2 .get() - .acquire(ctx, 0, TestUtils.onFailure2(err -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onFailure2(err -> { res.add(2); latch.countDown(); })); @@ -1189,13 +1192,13 @@ public Future> connect(ContextInternal context, Listen if (val == 0) { ref2 .get() - .acquire(ctx, 0, TestUtils.onFailure2(err -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onFailure2(err -> { res.add(3); latch.countDown(); })); ref1 .get() - .acquire(ctx, 0, TestUtils.onFailure2(err -> { + .acquire(ctx, 0, TIMEOUT, TestUtils.onFailure2(err -> { res.add(4); latch.countDown(); })); @@ -1212,7 +1215,7 @@ public boolean isValid(Connection connection) { }, new int[]{1}, 2); ref1.set(pool1); ref2.set(pool2); - pool1.acquire(ctx, 0, TestUtils.onFailure2(err -> res.add(0))); + pool1.acquire(ctx, 0, TIMEOUT, TestUtils.onFailure2(err -> res.add(0))); TestUtils.awaitLatch(latch); // assertEquals(Arrays.asList(0, 2, 1, 3, 4), res); } @@ -1267,10 +1270,10 @@ public void testMaxWaitersDoesNotBoundConnectionCreation() throws Exception { ConnectionManager mgr = new ConnectionManager(); ConnectionPool pool = pool(mgr, new int[] { 1 }, 0); Connection expected = new Connection(); - pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(expected, lease.get()); // The pool is full and waiting is not permitted - pool.acquire(context, 0, TestUtils.onFailure2(err -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onFailure2(err -> { Assert.assertTrue(err instanceof ConnectionPoolTooBusyException); testComplete(); })); 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 fd388e58435..6f91e04f38d 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 @@ -43,11 +43,11 @@ public void testStaleConnectionEviction() throws Exception { Connection conn1 = new Connection(); Connection conn2 = new Connection(); CountDownLatch latch = new CountDownLatch(2); - pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { lease.recycle(); latch.countDown(); })); - pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { lease.recycle(); latch.countDown(); })); @@ -69,7 +69,7 @@ public void testStaleConnectionEviction() throws Exception { // 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 -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(conn3, lease.get()); Assert.assertTrue(conn2.closed); testComplete(); @@ -88,7 +88,7 @@ public void testInvalidConnectionRetainedWhileBusy() throws Exception { .build(); Connection conn = new Connection(); AtomicReference> leaseRef = new AtomicReference<>(); - pool.acquire(context, 0, TestUtils.onSuccess2(leaseRef::set)); + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(leaseRef::set)); mgr.assertRequest().connect(conn, 0); assertWaitUntil(() -> leaseRef.get() != null); // A busy connection finishes its leases @@ -137,12 +137,12 @@ public void testConnectRetryDelay() throws Exception { .withMaxWaiters(10) .withConnectRetryDelay(Duration.ofMillis(20)) .build(); - pool.acquire(context, 0, (res, err) -> { + pool.acquire(context, 0, TIMEOUT, (res, err) -> { // Fails with the connect failure }); AtomicBoolean served = new AtomicBoolean(); Connection expected = new Connection(); - pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(expected, lease.get()); served.set(true); })); @@ -168,12 +168,12 @@ public void testConnectSuccessClearsRetryDelay() throws Exception { .withMaxWaiters(10) .withConnectRetryDelay(Duration.ofSeconds(10)) .build(); - pool.acquire(context, 0, (res, err) -> { + pool.acquire(context, 0, TIMEOUT, (res, err) -> { // Fails with the connect failure }); Connection conn1 = new Connection(); AtomicBoolean served = new AtomicBoolean(); - pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(conn1, lease.get()); served.set(true); })); @@ -185,7 +185,7 @@ public void testConnectSuccessClearsRetryDelay() throws Exception { // 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 -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(conn2, lease.get()); served2.set(true); })); @@ -218,7 +218,7 @@ public void testListenerServedByConnect() throws Exception { ConnectionPool pool = pool(mgr, new int[] { 1 }); EventListener listener = new EventListener(); // The acquisition waits covered by its own connect: the connect success dequeues it - pool.acquire(context, listener, 0, (res, err) -> listener.events.add("settled")); + pool.acquire(context, listener, 0, TIMEOUT, (res, err) -> listener.events.add("settled")); mgr.assertRequest().connect(new Connection(), 0); assertWaitUntil(() -> listener.events.contains("settled")); Assert.assertEquals(Arrays.asList("enqueue", "dequeue", "settled"), listener.events); @@ -230,7 +230,7 @@ public void testListenerConnectFailureSignalsDequeue() throws Exception { ConnectionManager mgr = new ConnectionManager(); ConnectionPool pool = pool(mgr, new int[] { 1 }); EventListener listener = new EventListener(); - pool.acquire(context, listener, 0, (res, err) -> listener.events.add("settled")); + pool.acquire(context, listener, 0, TIMEOUT, (res, err) -> listener.events.add("settled")); // The connect failure fails the head of the wait queue mgr.assertRequest().fail(new Exception("failure")); assertWaitUntil(() -> listener.events.contains("settled")); @@ -242,11 +242,11 @@ public void testListenerCloseSignalsDequeue() throws Exception { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); ConnectionPool pool = pool(mgr, new int[] { 1 }); - pool.acquire(context, 0, (res, err) -> { + pool.acquire(context, 0, TIMEOUT, (res, err) -> { }); mgr.assertRequest(); EventListener listener = new EventListener(); - pool.acquire(context, listener, 0, (res, err) -> listener.events.add("settled")); + pool.acquire(context, listener, 0, TIMEOUT, (res, err) -> listener.events.add("settled")); assertWaitUntil(() -> listener.events.contains("enqueue")); pool.close((res, err) -> { }); @@ -260,11 +260,11 @@ public void testListenerGrantSignalsDequeue() throws Exception { ConnectionManager mgr = new ConnectionManager(); ConnectionPool pool = pool(mgr, new int[] { 1 }); AtomicReference> leaseRef = new AtomicReference<>(); - pool.acquire(context, 0, TestUtils.onSuccess2(leaseRef::set)); + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(leaseRef::set)); mgr.assertRequest().connect(new Connection(), 0); assertWaitUntil(() -> leaseRef.get() != null); EventListener listener = new EventListener(); - pool.acquire(context, listener, 0, (res, err) -> listener.events.add("settled")); + pool.acquire(context, listener, 0, TIMEOUT, (res, err) -> listener.events.add("settled")); assertWaitUntil(() -> listener.events.contains("enqueue")); // The recycled connection serves the waiter leaseRef.get().recycle(); @@ -277,11 +277,11 @@ public void testListenerCancelSignalsDequeue() throws Exception { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); ConnectionPool pool = pool(mgr, new int[] { 1 }); - pool.acquire(context, 0, (res, err) -> { + pool.acquire(context, 0, TIMEOUT, (res, err) -> { }); mgr.assertRequest(); EventListener listener = new EventListener(); - pool.acquire(context, listener, 0, (res, err) -> listener.events.add("settled")); + pool.acquire(context, listener, 0, TIMEOUT, (res, err) -> listener.events.add("settled")); assertWaitUntil(() -> listener.waiter != null); AtomicBoolean cancelled = new AtomicBoolean(); pool.cancel(listener.waiter, TestUtils.onSuccess2(cancelled::set)); @@ -294,7 +294,7 @@ public void testListenerTimeoutSignalsDequeue() throws Exception { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); ConnectionPool pool = pool(mgr, new int[] { 1 }); - pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { // The connection is held, the next acquisition waits })); mgr.assertRequest().connect(new Connection(), 0); @@ -307,6 +307,23 @@ public void testListenerTimeoutSignalsDequeue() throws Exception { Assert.assertEquals(Arrays.asList("enqueue", "timeout"), listener.events); } + @Test + public void testAcquireTimeoutRequired() throws Exception { + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = pool(mgr, new int[] { 1 }); + ContextInternal context = vertx.createEventLoopContext(); + AtomicReference failure = new AtomicReference<>(); + pool.acquire(context, 0, (res, err) -> failure.set(err)); + assertWaitUntil(() -> failure.get() instanceof IllegalArgumentException); + failure.set(null); + pool.acquire(context, 0, Duration.ZERO, (res, err) -> failure.set(err)); + assertWaitUntil(() -> failure.get() instanceof IllegalArgumentException); + failure.set(null); + pool.acquire(context, 0, Duration.ofSeconds(-1), (res, err) -> failure.set(err)); + assertWaitUntil(() -> failure.get() instanceof IllegalArgumentException); + mgr.assertNoRequest(); + } + @Test public void testKindChange() { ContextInternal context = vertx.createEventLoopContext(); @@ -314,14 +331,14 @@ public void testKindChange() { ConnectionPool pool = pool(mgr, new int[] { 5, 1 }); Connection conn1 = new Connection(); AtomicBoolean served = new AtomicBoolean(); - pool.acquire(context, 1, TestUtils.onSuccess2(lease -> { + pool.acquire(context, 1, TIMEOUT, 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 -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(conn2, lease.get()); served2.set(true); })); @@ -340,7 +357,7 @@ public void testAcquireTimeout() throws Exception { ConnectionManager mgr = new ConnectionManager(); ConnectionPool pool = pool(mgr, new int[] { 1 }); Connection conn1 = new Connection(); - pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { // The connection is held, the next acquisition waits })); mgr.assertRequest().connect(conn1, 0); @@ -367,7 +384,7 @@ public void testConnectFailureRetainsWaiterTimeout() throws Exception { ConnectionPool pool = pool(mgr, new int[] { 1 }); // A first acquisition connects AtomicBoolean failed = new AtomicBoolean(); - pool.acquire(context, 0, (res, err) -> { + pool.acquire(context, 0, TIMEOUT, (res, err) -> { if (err != null) { failed.set(true); } @@ -382,7 +399,7 @@ public void onDequeue(PoolWaiter waiter, boolean timeout) { } }, 0, Duration.ofMillis(10), (res, err) -> { }); - pool.acquire(context, 0, (res, err) -> { + pool.acquire(context, 0, TIMEOUT, (res, err) -> { }); Thread.sleep(20); // The connect failure opens the round: the timed out waiter eviction and the connect failure @@ -430,7 +447,7 @@ public void testMinSize() throws Exception { assertWaitUntil(() -> pool.size() == 3); // An acquisition is served from the pooled connections AtomicBoolean served = new AtomicBoolean(); - pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { served.set(true); })); assertWaitUntil(served::get); @@ -452,7 +469,7 @@ public void testMinSizeCoversWaiter() throws Exception { // 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 -> { + pool.acquire(context, 0, TIMEOUT, TestUtils.onSuccess2(lease -> { Assert.assertSame(expected, lease.get()); served.set(true); })); 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 1997775a560..68527ed3e85 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 @@ -11,6 +11,7 @@ package io.vertx.tests.pool; +import java.time.Duration; import io.vertx.core.*; import io.vertx.core.internal.ContextInternal; import io.vertx.core.internal.pool.ConnectResult; @@ -28,6 +29,8 @@ */ public class StressTest extends VertxTestBase { + static final Duration TIMEOUT = Duration.ofMinutes(10); + protected ConnectionPool pool(PoolConnector connector, int[] maxSizes, int maxWaiters) { return ConnectionPool.pool(connector, maxSizes, maxWaiters); } @@ -42,7 +45,7 @@ class FakeConnectionPool implements PoolConnector { void getConnection(FakeWaiter waiter) { pool - .acquire(waiter.context, 0, (res, err) -> { + .acquire(waiter.context, 0, TIMEOUT, (res, err) -> { if (err == null) { waiter.handleConnection(res); } else {