You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hc.apache.org by ol...@apache.org on 2025/09/14 13:02:19 UTC

(httpcomponents-client) branch 5.5.x updated: Imporved TestAsyncClient wiring; added internal methods to get the underlying connection from the connection endpoint; coverage for async connection management operations

This is an automated email from the ASF dual-hosted git repository.

olegk pushed a commit to branch 5.5.x
in repository https://gitbox.apache.org/repos/asf/httpcomponents-client.git


The following commit(s) were added to refs/heads/5.5.x by this push:
     new da1a8e0fe Imporved TestAsyncClient wiring; added internal methods to get the underlying connection from the connection endpoint; coverage for async connection management operations
da1a8e0fe is described below

commit da1a8e0fed0d83a14c4e39895ac190fdcfe18c4c
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Sun Sep 14 14:29:48 2025 +0200

    Imporved TestAsyncClient wiring; added internal methods to get the underlying connection from the connection endpoint; coverage for async connection management operations
---
 .../async/TestAsyncConnectionManagement.java       | 315 +++++++++++++++++++++
 .../extension/async/MinimalTestClientBuilder.java  |  27 +-
 .../extension/async/StandardTestClientBuilder.java |  17 +-
 .../testing/extension/async/TestAsyncClient.java   |  13 +-
 .../extension/async/TestAsyncClientBuilder.java    |   9 +-
 .../testing/extension/sync/TestClientBuilder.java  |   4 +-
 .../testing/sync/TestConnectionManagement.java     |   4 +-
 .../hc/client5/http/impl/ConnectionHolder.java     |  41 +++
 .../impl/async/AbstractHttpAsyncClientBase.java    |  19 +-
 .../impl/io/BasicHttpClientConnectionManager.java  |   9 +-
 .../io/PoolingHttpClientConnectionManager.java     |  10 +-
 .../nio/PoolingAsyncClientConnectionManager.java   |  10 +-
 12 files changed, 447 insertions(+), 31 deletions(-)

diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestAsyncConnectionManagement.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestAsyncConnectionManagement.java
new file mode 100644
index 000000000..fa6f35ab5
--- /dev/null
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestAsyncConnectionManagement.java
@@ -0,0 +1,315 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation.  For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.client5.testing.async;
+
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import org.apache.hc.client5.http.HttpRoute;
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
+import org.apache.hc.client5.http.async.methods.SimpleRequestProducer;
+import org.apache.hc.client5.http.async.methods.SimpleResponseConsumer;
+import org.apache.hc.client5.http.config.ConnectionConfig;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
+import org.apache.hc.client5.http.nio.AsyncConnectionEndpoint;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+import org.apache.hc.client5.testing.extension.async.ClientProtocolLevel;
+import org.apache.hc.client5.testing.extension.async.ServerProtocolLevel;
+import org.apache.hc.client5.testing.extension.async.TestAsyncClient;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpHeaders;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.URIScheme;
+import org.apache.hc.core5.http.protocol.HttpCoreContext;
+import org.apache.hc.core5.pool.PoolConcurrencyPolicy;
+import org.apache.hc.core5.pool.PoolReusePolicy;
+import org.apache.hc.core5.util.TimeValue;
+import org.apache.hc.core5.util.Timeout;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+class TestAsyncConnectionManagement extends AbstractIntegrationTestBase {
+
+    static final Timeout TIMEOUT = Timeout.ofSeconds(30);
+    static final Timeout LEASE_TIMEOUT = Timeout.ofSeconds(5);
+
+    public TestAsyncConnectionManagement() {
+        super(URIScheme.HTTP, ClientProtocolLevel.STANDARD, ServerProtocolLevel.STANDARD);
+    }
+
+    @BeforeEach
+    void setup() {
+        configureServer(bootstrap -> bootstrap.register("*", () -> new AbstractSimpleServerExchangeHandler() {
+
+            @Override
+            protected SimpleHttpResponse handle(
+                    final SimpleHttpRequest request,
+                    final HttpCoreContext context) {
+                final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_OK);
+                response.setBody("Whatever", ContentType.TEXT_PLAIN);
+                return response;
+            }
+        }));
+    }
+
+    /**
+     * Tests releasing and re-using a connection after a response is read.
+     */
+    @Test
+    void testReleaseConnection() throws Exception {
+        final HttpHost target = startServer();
+
+        final PoolingAsyncClientConnectionManager connManager = PoolingAsyncClientConnectionManagerBuilder.create()
+                .build();
+        configureClient(builder -> builder.setConnectionManager(connManager));
+        final TestAsyncClient client = startClient();
+
+        connManager.setMaxTotal(1);
+
+        final HttpRoute route = new HttpRoute(target, null, false);
+        final HttpClientContext context = HttpClientContext.create();
+
+        final Future<AsyncConnectionEndpoint> endpointFuture1 = connManager.lease("id1", route, null, TIMEOUT, null);
+        final AsyncConnectionEndpoint endpoint1 = endpointFuture1.get(LEASE_TIMEOUT.getDuration(), LEASE_TIMEOUT.getTimeUnit());
+
+        final Future<AsyncConnectionEndpoint> connectFuture1 = connManager.connect(endpoint1, client.getImplementation(), TIMEOUT, null, context, null);
+        final AsyncConnectionEndpoint openEndpoint1 = connectFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
+
+        final SimpleHttpRequest request = SimpleRequestBuilder.get()
+                .setHttpHost(target)
+                .setPath("/")
+                .addHeader(HttpHeaders.HOST, target.toHostString())
+                .build();
+
+        final Future<SimpleHttpResponse> responseFuture1 = openEndpoint1.execute("ex-1", SimpleRequestProducer.create(request), SimpleResponseConsumer.create(), null);
+        final SimpleHttpResponse response1 = responseFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
+        Assertions.assertEquals(HttpStatus.SC_OK, response1.getCode());
+
+        // this should fail quickly, connection has not been released
+        final Future<AsyncConnectionEndpoint> endpointFuture2 = connManager.lease("id2", route, null, TIMEOUT, null);
+        Assertions.assertThrows(TimeoutException.class, () -> endpointFuture2.get(10, TimeUnit.MILLISECONDS));
+        endpointFuture2.cancel(true);
+
+        // close and release the connection
+        // expect the next connection obtained to be closed
+        openEndpoint1.close();
+        connManager.release(openEndpoint1, null, TimeValue.NEG_ONE_MILLISECOND);
+
+        final Future<AsyncConnectionEndpoint> endpointFuture3 = connManager.lease("id3", route, null, TIMEOUT, null);
+        final AsyncConnectionEndpoint endpoint2 = endpointFuture3.get(LEASE_TIMEOUT.getDuration(), LEASE_TIMEOUT.getTimeUnit());
+        Assertions.assertFalse(endpoint2.isConnected());
+
+        final Future<AsyncConnectionEndpoint> connectFuture2 = connManager.connect(endpoint2, client.getImplementation(), TIMEOUT, null, context, null);
+        final AsyncConnectionEndpoint openEndpoint2 = connectFuture2.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
+
+        final Future<SimpleHttpResponse> responseFuture2 = openEndpoint2.execute("ex-2", SimpleRequestProducer.create(request), SimpleResponseConsumer.create(), null);
+        final SimpleHttpResponse response2 = responseFuture2.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
+        Assertions.assertEquals(HttpStatus.SC_OK, response2.getCode());
+
+        // release connection keeping it open
+        // expect the next connection obtained to be open
+        connManager.release(openEndpoint2, null, TimeValue.NEG_ONE_MILLISECOND);
+
+        final Future<AsyncConnectionEndpoint> endpointFuture4 = connManager.lease("id4", route, null, TIMEOUT, null);
+        final AsyncConnectionEndpoint openEndpoint3 = endpointFuture4.get(LEASE_TIMEOUT.getDuration(), LEASE_TIMEOUT.getTimeUnit());
+        Assertions.assertTrue(openEndpoint3.isConnected());
+
+        final Future<SimpleHttpResponse> responseFuture3 = openEndpoint3.execute("ex-3", SimpleRequestProducer.create(request), SimpleResponseConsumer.create(), null);
+        final SimpleHttpResponse response3 = responseFuture3.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
+        Assertions.assertEquals(HttpStatus.SC_OK, response3.getCode());
+
+        connManager.release(openEndpoint3, null, TimeValue.NEG_ONE_MILLISECOND);
+        connManager.close();
+    }
+
+    /**
+     * Tests releasing with time limits.
+     */
+    @Test
+    void testReleaseConnectionWithTimeLimits() throws Exception {
+        final HttpHost target = startServer();
+
+        final PoolingAsyncClientConnectionManager connManager = PoolingAsyncClientConnectionManagerBuilder.create()
+                .build();
+        configureClient(builder -> builder.setConnectionManager(connManager));
+        final TestAsyncClient client = startClient();
+
+        connManager.setMaxTotal(1);
+
+        final HttpRoute route = new HttpRoute(target, null, false);
+        final HttpClientContext context = HttpClientContext.create();
+
+        final Future<AsyncConnectionEndpoint> endpointFuture1 = connManager.lease("id1", route, null, TIMEOUT, null);
+        final AsyncConnectionEndpoint endpoint1 = endpointFuture1.get(LEASE_TIMEOUT.getDuration(), LEASE_TIMEOUT.getTimeUnit());
+
+        final Future<AsyncConnectionEndpoint> connectFuture1 = connManager.connect(endpoint1, client.getImplementation(), TIMEOUT, null, context, null);
+        final AsyncConnectionEndpoint openEndpoint1 = connectFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
+
+        final SimpleHttpRequest request = SimpleRequestBuilder.get()
+                .setHttpHost(target)
+                .setPath("/")
+                .addHeader(HttpHeaders.HOST, target.toHostString())
+                .build();
+
+        final Future<SimpleHttpResponse> responseFuture1 = openEndpoint1.execute("ex-1", SimpleRequestProducer.create(request), SimpleResponseConsumer.create(), null);
+        final SimpleHttpResponse response1 = responseFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
+        Assertions.assertEquals(HttpStatus.SC_OK, response1.getCode());
+
+        final Future<AsyncConnectionEndpoint> endpointFuture2 = connManager.lease("id2", route, null, TIMEOUT, null);
+        Assertions.assertThrows(TimeoutException.class, () -> endpointFuture2.get(10, TimeUnit.MILLISECONDS));
+        endpointFuture2.cancel(true);
+
+        openEndpoint1.close();
+        connManager.release(openEndpoint1, null, TimeValue.NEG_ONE_MILLISECOND);
+
+        final Future<AsyncConnectionEndpoint> endpointFuture3 = connManager.lease("id3", route, null, TIMEOUT, null);
+        final AsyncConnectionEndpoint endpoint2 = endpointFuture3.get(LEASE_TIMEOUT.getDuration(), LEASE_TIMEOUT.getTimeUnit());
+        Assertions.assertFalse(endpoint2.isConnected());
+
+        final Future<AsyncConnectionEndpoint> connectFuture2 = connManager.connect(endpoint2, client.getImplementation(), TIMEOUT, null, context, null);
+        final AsyncConnectionEndpoint openEndpoint2 = connectFuture2.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
+
+        final Future<SimpleHttpResponse> responseFuture2 = openEndpoint2.execute("ex-2", SimpleRequestProducer.create(request), SimpleResponseConsumer.create(), null);
+        final SimpleHttpResponse response2 = responseFuture2.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
+        Assertions.assertEquals(HttpStatus.SC_OK, response2.getCode());
+
+        connManager.release(openEndpoint2, null, TimeValue.ofMilliseconds(100));
+        Thread.sleep(150);
+
+        final Future<AsyncConnectionEndpoint> endpointFuture4 = connManager.lease("id4", route, null, TIMEOUT, null);
+        final AsyncConnectionEndpoint openEndpoint3 = endpointFuture4.get(LEASE_TIMEOUT.getDuration(), LEASE_TIMEOUT.getTimeUnit());
+        Assertions.assertFalse(openEndpoint3.isConnected());
+        connManager.release(openEndpoint3, null, TimeValue.ofMilliseconds(100));
+
+        connManager.close();
+    }
+
+    @Test
+    void testCloseExpiredIdleConnections() throws Exception {
+        final HttpHost target = startServer();
+
+        final PoolingAsyncClientConnectionManager connManager = PoolingAsyncClientConnectionManagerBuilder.create()
+                .build();
+        configureClient(builder -> builder.setConnectionManager(connManager));
+        final TestAsyncClient client = startClient();
+
+        connManager.setMaxTotal(1);
+
+        final HttpRoute route = new HttpRoute(target, null, false);
+        final HttpClientContext context = HttpClientContext.create();
+
+        final Future<AsyncConnectionEndpoint> endpointFuture1 = connManager.lease("id1", route, null, TIMEOUT, null);
+        final AsyncConnectionEndpoint endpoint1 = endpointFuture1.get(LEASE_TIMEOUT.getDuration(), LEASE_TIMEOUT.getTimeUnit());
+
+        connManager.connect(endpoint1, client.getImplementation(), TIMEOUT, null, context, null)
+                .get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
+
+        Assertions.assertEquals(1, connManager.getTotalStats().getLeased());
+        Assertions.assertEquals(1, connManager.getStats(route).getLeased());
+
+        connManager.release(endpoint1, null, TimeValue.ofMilliseconds(100));
+
+        // Released, still active.
+        Assertions.assertEquals(1, connManager.getTotalStats().getAvailable());
+        Assertions.assertEquals(1, connManager.getStats(route).getAvailable());
+
+        connManager.closeExpired();
+
+        // Time has not expired yet.
+        Assertions.assertEquals(1, connManager.getTotalStats().getAvailable());
+        Assertions.assertEquals(1, connManager.getStats(route).getAvailable());
+
+        Thread.sleep(150);
+
+        connManager.closeExpired();
+
+        // Time expired now, connections are destroyed.
+        Assertions.assertEquals(0, connManager.getTotalStats().getAvailable());
+        Assertions.assertEquals(0, connManager.getStats(route).getAvailable());
+
+        connManager.close();
+    }
+
+    @Test
+    void testCloseExpiredTTLConnections() throws Exception {
+        final HttpHost target = startServer();
+
+        final PoolingAsyncClientConnectionManager connManager = PoolingAsyncClientConnectionManagerBuilder.create()
+                .setPoolConcurrencyPolicy(PoolConcurrencyPolicy.STRICT)
+                .setConnPoolPolicy(PoolReusePolicy.LIFO)
+                .setDefaultConnectionConfig(ConnectionConfig.custom()
+                        .setTimeToLive(TimeValue.ofMilliseconds(100))
+                        .build())
+                .build();
+        configureClient(builder -> builder.setConnectionManager(connManager));
+
+        final TestAsyncClient client = startClient();
+
+        connManager.setMaxTotal(1);
+
+        final HttpRoute route = new HttpRoute(target, null, false);
+        final HttpClientContext context = HttpClientContext.create();
+
+        final Future<AsyncConnectionEndpoint> endpointFuture1 = connManager.lease("id1", route, null, TIMEOUT, null);
+        final AsyncConnectionEndpoint endpoint1 = endpointFuture1.get(LEASE_TIMEOUT.getDuration(), LEASE_TIMEOUT.getTimeUnit());
+
+        connManager.connect(endpoint1, client.getImplementation(), TIMEOUT, null, context, null)
+                .get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
+
+        Assertions.assertEquals(1, connManager.getTotalStats().getLeased());
+        Assertions.assertEquals(1, connManager.getStats(route).getLeased());
+        // Release, let remain idle for forever
+        connManager.release(endpoint1, null, TimeValue.NEG_ONE_MILLISECOND);
+
+        // Released, still active.
+        Assertions.assertEquals(1, connManager.getTotalStats().getAvailable());
+        Assertions.assertEquals(1, connManager.getStats(route).getAvailable());
+
+        connManager.closeExpired();
+
+        // Time has not expired yet.
+        Assertions.assertEquals(1, connManager.getTotalStats().getAvailable());
+        Assertions.assertEquals(1, connManager.getStats(route).getAvailable());
+
+        Thread.sleep(150);
+
+        connManager.closeExpired();
+
+        // TTL expired now, connections are destroyed.
+        Assertions.assertEquals(0, connManager.getTotalStats().getAvailable());
+        Assertions.assertEquals(0, connManager.getStats(route).getAvailable());
+
+        connManager.close();
+    }
+
+}
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/MinimalTestClientBuilder.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/MinimalTestClientBuilder.java
index 5c8b1c0a9..e99a78c67 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/MinimalTestClientBuilder.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/MinimalTestClientBuilder.java
@@ -31,8 +31,8 @@
 import org.apache.hc.client5.http.config.TlsConfig;
 import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
 import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
-import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
 import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
+import org.apache.hc.client5.http.nio.AsyncClientConnectionManager;
 import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
 import org.apache.hc.client5.testing.SSLTestContexts;
 import org.apache.hc.core5.http.config.Http1Config;
@@ -45,6 +45,7 @@ final class MinimalTestClientBuilder implements TestAsyncClientBuilder {
 
     private final PoolingAsyncClientConnectionManagerBuilder connectionManagerBuilder;
 
+    private AsyncClientConnectionManager connectionManager;
     private Timeout timeout;
     private TlsStrategy tlsStrategy;
     private Http1Config http1Config;
@@ -65,6 +66,12 @@ public TestAsyncClientBuilder setTimeout(final Timeout timeout) {
         return this;
     }
 
+    @Override
+    public TestAsyncClientBuilder setConnectionManager(final AsyncClientConnectionManager connectionManager) {
+        this.connectionManager = connectionManager;
+        return this;
+    }
+
     @Override
     public TestAsyncClientBuilder setTlsStrategy(final TlsStrategy tlsStrategy) {
         this.tlsStrategy = tlsStrategy;
@@ -97,21 +104,21 @@ public TestAsyncClientBuilder setH2Config(final H2Config h2Config) {
 
     @Override
     public TestAsyncClient build() throws Exception {
-        final PoolingAsyncClientConnectionManager connectionManager = connectionManagerBuilder
+        final AsyncClientConnectionManager connectionManagerCopy = connectionManager == null ? connectionManagerBuilder
                 .setTlsStrategy(tlsStrategy != null ? tlsStrategy : new DefaultClientTlsStrategy(SSLTestContexts.createClientSSLContext()))
                 .setDefaultConnectionConfig(ConnectionConfig.custom()
                         .setSocketTimeout(timeout)
                         .setConnectTimeout(timeout)
                         .build())
-                .build();
+                .build() : connectionManager;
         final CloseableHttpAsyncClient client = HttpAsyncClients.createMinimal(
-                        h2Config,
-                        http1Config,
-                        IOReactorConfig.custom()
-                                .setSoTimeout(timeout)
-                                .build(),
-                connectionManager);
-        return new TestAsyncClient(client, connectionManager);
+                h2Config,
+                http1Config,
+                IOReactorConfig.custom()
+                        .setSoTimeout(timeout)
+                        .build(),
+                connectionManagerCopy);
+        return new TestAsyncClient(client, connectionManagerCopy);
     }
 
 }
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/StandardTestClientBuilder.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/StandardTestClientBuilder.java
index 1df164a8c..11c291686 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/StandardTestClientBuilder.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/StandardTestClientBuilder.java
@@ -38,8 +38,8 @@
 import org.apache.hc.client5.http.config.TlsConfig;
 import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
 import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder;
-import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
 import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
+import org.apache.hc.client5.http.nio.AsyncClientConnectionManager;
 import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
 import org.apache.hc.client5.testing.SSLTestContexts;
 import org.apache.hc.core5.http.Header;
@@ -57,6 +57,7 @@ final class StandardTestClientBuilder implements TestAsyncClientBuilder {
     private final PoolingAsyncClientConnectionManagerBuilder connectionManagerBuilder;
     private final HttpAsyncClientBuilder clientBuilder;
 
+    private AsyncClientConnectionManager connectionManager;
     private Timeout timeout;
     private TlsStrategy tlsStrategy;
 
@@ -76,6 +77,12 @@ public TestAsyncClientBuilder setTimeout(final Timeout timeout) {
         return this;
     }
 
+    @Override
+    public TestAsyncClientBuilder setConnectionManager(final AsyncClientConnectionManager connectionManager) {
+        this.connectionManager = connectionManager;
+        return this;
+    }
+
     @Override
     public TestAsyncClientBuilder addResponseInterceptorFirst(final HttpResponseInterceptor interceptor) {
         this.clientBuilder.addResponseInterceptorFirst(interceptor);
@@ -168,20 +175,20 @@ public TestAsyncClientBuilder setDefaultCredentialsProvider(final CredentialsPro
 
     @Override
     public TestAsyncClient build() throws Exception {
-        final PoolingAsyncClientConnectionManager connectionManager = connectionManagerBuilder
+        final AsyncClientConnectionManager connectionManagerCopy = connectionManager == null ? connectionManagerBuilder
                 .setTlsStrategy(tlsStrategy != null ? tlsStrategy : new DefaultClientTlsStrategy(SSLTestContexts.createClientSSLContext()))
                 .setDefaultConnectionConfig(ConnectionConfig.custom()
                         .setSocketTimeout(timeout)
                         .setConnectTimeout(timeout)
                         .build())
-                .build();
+                .build() : connectionManager;
         final CloseableHttpAsyncClient client = clientBuilder
                 .setIOReactorConfig(IOReactorConfig.custom()
                         .setSoTimeout(timeout)
                         .build())
-                .setConnectionManager(connectionManager)
+                .setConnectionManager(connectionManagerCopy)
                 .build();
-        return new TestAsyncClient(client, connectionManager);
+        return new TestAsyncClient(client, connectionManagerCopy);
     }
 
 }
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/TestAsyncClient.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/TestAsyncClient.java
index adefc4560..30563ebf2 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/TestAsyncClient.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/TestAsyncClient.java
@@ -31,7 +31,7 @@
 import java.util.concurrent.Future;
 
 import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
-import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
+import org.apache.hc.client5.http.nio.AsyncClientConnectionManager;
 import org.apache.hc.core5.concurrent.FutureCallback;
 import org.apache.hc.core5.function.Supplier;
 import org.apache.hc.core5.http.HttpHost;
@@ -43,16 +43,15 @@
 import org.apache.hc.core5.io.CloseMode;
 import org.apache.hc.core5.reactor.IOReactorStatus;
 import org.apache.hc.core5.util.Args;
-import org.apache.hc.core5.util.Asserts;
 import org.apache.hc.core5.util.TimeValue;
 
 public class TestAsyncClient extends CloseableHttpAsyncClient {
 
     private final CloseableHttpAsyncClient client;
-    private final PoolingAsyncClientConnectionManager connectionManager;
+    private final AsyncClientConnectionManager connectionManager;
 
     public TestAsyncClient(final CloseableHttpAsyncClient client,
-                           final PoolingAsyncClientConnectionManager connectionManager) {
+                           final AsyncClientConnectionManager connectionManager) {
         this.client = Args.notNull(client, "Client");
         this.connectionManager = connectionManager;
     }
@@ -113,9 +112,9 @@ public <T extends CloseableHttpAsyncClient> T getImplementation() {
         return (T) client;
     }
 
-    public PoolingAsyncClientConnectionManager getConnectionManager() {
-        Asserts.check(connectionManager != null, "Connection manager is not available");
-        return connectionManager;
+    @SuppressWarnings("unchecked")
+    public <T extends AsyncClientConnectionManager> T getConnectionManager() {
+        return (T) connectionManager;
     }
 
 }
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/TestAsyncClientBuilder.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/TestAsyncClientBuilder.java
index 3f12b77cf..cbb2878ef 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/TestAsyncClientBuilder.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/TestAsyncClientBuilder.java
@@ -35,6 +35,7 @@
 import org.apache.hc.client5.http.auth.AuthSchemeFactory;
 import org.apache.hc.client5.http.auth.CredentialsProvider;
 import org.apache.hc.client5.http.config.TlsConfig;
+import org.apache.hc.client5.http.nio.AsyncClientConnectionManager;
 import org.apache.hc.core5.http.Header;
 import org.apache.hc.core5.http.HttpRequestInterceptor;
 import org.apache.hc.core5.http.HttpResponseInterceptor;
@@ -50,8 +51,12 @@ public interface TestAsyncClientBuilder {
 
     TestAsyncClientBuilder setTimeout(Timeout soTimeout);
 
-    default TestAsyncClientBuilder addResponseInterceptorFirst(final HttpResponseInterceptor interceptor) {
-        return this;
+    default TestAsyncClientBuilder setConnectionManager(AsyncClientConnectionManager connManager) {
+        throw new UnsupportedOperationException("Operation not supported by " + getProtocolLevel());
+    }
+
+    default TestAsyncClientBuilder addResponseInterceptorFirst(HttpResponseInterceptor interceptor) {
+        throw new UnsupportedOperationException("Operation not supported by " + getProtocolLevel());
     }
 
     default TestAsyncClientBuilder addResponseInterceptorLast(HttpResponseInterceptor interceptor) {
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/sync/TestClientBuilder.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/sync/TestClientBuilder.java
index 459124693..57526ef2c 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/sync/TestClientBuilder.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/sync/TestClientBuilder.java
@@ -51,8 +51,8 @@ public interface TestClientBuilder {
 
     TestClientBuilder setConnectionManager(HttpClientConnectionManager connManager);
 
-    default TestClientBuilder addResponseInterceptorFirst(final HttpResponseInterceptor interceptor) {
-        return this;
+    default TestClientBuilder addResponseInterceptorFirst(HttpResponseInterceptor interceptor) {
+        throw new UnsupportedOperationException("Operation not supported by " + getProtocolLevel());
     }
 
     default TestClientBuilder addResponseInterceptorLast(HttpResponseInterceptor interceptor) {
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionManagement.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionManagement.java
index 8c215b2a8..c46f98e87 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionManagement.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionManagement.java
@@ -129,6 +129,8 @@ void testReleaseConnection() throws Exception {
         final LeaseRequest leaseRequest2 = connManager.lease("id2", route, null);
         Assertions.assertThrows(TimeoutException.class, () -> leaseRequest2.get(Timeout.ofMilliseconds(10)));
 
+        // close and release the connection
+        // expect the next connection obtained to be closed
         endpoint1.close();
         connManager.release(endpoint1, null, TimeValue.NEG_ONE_MILLISECOND);
         final LeaseRequest leaseRequest3 = connManager.lease("id2", route, null);
@@ -141,7 +143,7 @@ void testReleaseConnection() throws Exception {
             Assertions.assertEquals(HttpStatus.SC_OK, response2.getCode());
         }
 
-        // release connection after marking it for re-use
+        // release connection keeping it open
         // expect the next connection obtained to be open
         connManager.release(endpoint2, null, TimeValue.NEG_ONE_MILLISECOND);
 
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/ConnectionHolder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/ConnectionHolder.java
new file mode 100644
index 000000000..33a1d3d04
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/ConnectionHolder.java
@@ -0,0 +1,41 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation.  For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.client5.http.impl;
+
+import org.apache.hc.core5.annotation.Internal;
+import org.apache.hc.core5.http.HttpConnection;
+
+/**
+ * Internal interface to expose the underlying connection
+ * @since 5.5
+ */
+@Internal
+public interface ConnectionHolder {
+
+    HttpConnection get();
+
+}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AbstractHttpAsyncClientBase.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AbstractHttpAsyncClientBase.java
index 264faa2c7..e6b859c33 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AbstractHttpAsyncClientBase.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AbstractHttpAsyncClientBase.java
@@ -26,22 +26,28 @@
  */
 package org.apache.hc.client5.http.impl.async;
 
+import java.net.SocketAddress;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.atomic.AtomicReference;
 
+import org.apache.hc.core5.concurrent.FutureCallback;
 import org.apache.hc.core5.function.Supplier;
 import org.apache.hc.core5.http.nio.AsyncPushConsumer;
 import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.net.NamedEndpoint;
 import org.apache.hc.core5.reactor.ConnectionInitiator;
 import org.apache.hc.core5.reactor.DefaultConnectingIOReactor;
 import org.apache.hc.core5.reactor.IOReactorStatus;
+import org.apache.hc.core5.reactor.IOSession;
 import org.apache.hc.core5.util.TimeValue;
+import org.apache.hc.core5.util.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-abstract class AbstractHttpAsyncClientBase extends CloseableHttpAsyncClient {
+abstract class AbstractHttpAsyncClientBase extends CloseableHttpAsyncClient implements ConnectionInitiator {
 
     enum Status { READY, RUNNING, TERMINATED }
 
@@ -84,6 +90,17 @@ boolean isRunning() {
         return status.get() == Status.RUNNING;
     }
 
+    @Override
+    public Future<IOSession> connect(
+            final NamedEndpoint remoteEndpoint,
+            final SocketAddress remoteAddress,
+            final SocketAddress localAddress,
+            final Timeout timeout,
+            final Object attachment,
+            final FutureCallback<IOSession> callback) {
+        return ioReactor.connect(remoteEndpoint, remoteAddress, localAddress, timeout, attachment, callback);
+    }
+
     ConnectionInitiator getConnectionInitiator() {
         return ioReactor;
     }
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/BasicHttpClientConnectionManager.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/BasicHttpClientConnectionManager.java
index ef99e7872..9ca40f998 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/BasicHttpClientConnectionManager.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/BasicHttpClientConnectionManager.java
@@ -44,6 +44,7 @@
 import org.apache.hc.client5.http.config.ConnectionConfig;
 import org.apache.hc.client5.http.config.TlsConfig;
 import org.apache.hc.client5.http.impl.ConnPoolSupport;
+import org.apache.hc.client5.http.impl.ConnectionHolder;
 import org.apache.hc.client5.http.impl.ConnectionShutdownException;
 import org.apache.hc.client5.http.io.ConnectionEndpoint;
 import org.apache.hc.client5.http.io.HttpClientConnectionManager;
@@ -56,6 +57,7 @@
 import org.apache.hc.core5.annotation.ThreadingBehavior;
 import org.apache.hc.core5.http.ClassicHttpRequest;
 import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.HttpConnection;
 import org.apache.hc.core5.http.HttpException;
 import org.apache.hc.core5.http.HttpHost;
 import org.apache.hc.core5.http.URIScheme;
@@ -590,7 +592,7 @@ public void setValidateAfterInactivity(final TimeValue validateAfterInactivity)
                 .build();
     }
 
-    class InternalConnectionEndpoint extends ConnectionEndpoint implements Identifiable {
+    class InternalConnectionEndpoint extends ConnectionEndpoint implements ConnectionHolder, Identifiable {
 
         private final HttpRoute route;
         private final AtomicReference<ManagedHttpClientConnection> connRef;
@@ -703,6 +705,11 @@ public EndpointInfo getInfo() {
             return null;
         }
 
+        @Override
+        public HttpConnection get() {
+            return this.connRef.get();
+        }
+
     }
 
     /**
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManager.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManager.java
index bf674f96c..e027f56a8 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManager.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManager.java
@@ -42,6 +42,7 @@
 import org.apache.hc.client5.http.config.ConnectionConfig;
 import org.apache.hc.client5.http.config.TlsConfig;
 import org.apache.hc.client5.http.impl.ConnPoolSupport;
+import org.apache.hc.client5.http.impl.ConnectionHolder;
 import org.apache.hc.client5.http.impl.ConnectionShutdownException;
 import org.apache.hc.client5.http.impl.PrefixedIncrementingId;
 import org.apache.hc.client5.http.io.ConnectionEndpoint;
@@ -57,6 +58,7 @@
 import org.apache.hc.core5.function.Resolver;
 import org.apache.hc.core5.http.ClassicHttpRequest;
 import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.HttpConnection;
 import org.apache.hc.core5.http.HttpException;
 import org.apache.hc.core5.http.HttpHost;
 import org.apache.hc.core5.http.URIScheme;
@@ -689,7 +691,7 @@ public void setValidateAfterInactivity(final TimeValue validateAfterInactivity)
 
     private static final PrefixedIncrementingId INCREMENTING_ID = new PrefixedIncrementingId("ep-");
 
-    static class InternalConnectionEndpoint extends ConnectionEndpoint implements Identifiable {
+    static class InternalConnectionEndpoint extends ConnectionEndpoint implements ConnectionHolder, Identifiable {
 
         private final AtomicReference<PoolEntry<HttpRoute, ManagedHttpClientConnection>> poolEntryRef;
         private final String id;
@@ -806,6 +808,12 @@ public EndpointInfo getInfo() {
             return null;
         }
 
+        @Override
+        public HttpConnection get() {
+            final PoolEntry<HttpRoute, ManagedHttpClientConnection> poolEntry = poolEntryRef.get();
+            return poolEntry != null ? poolEntry.getConnection() : null;
+        }
+
     }
 
     /**
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/PoolingAsyncClientConnectionManager.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/PoolingAsyncClientConnectionManager.java
index 3fbf34d19..be7b5348e 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/PoolingAsyncClientConnectionManager.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/PoolingAsyncClientConnectionManager.java
@@ -42,6 +42,7 @@
 import org.apache.hc.client5.http.config.ConnectionConfig;
 import org.apache.hc.client5.http.config.TlsConfig;
 import org.apache.hc.client5.http.impl.ConnPoolSupport;
+import org.apache.hc.client5.http.impl.ConnectionHolder;
 import org.apache.hc.client5.http.impl.ConnectionShutdownException;
 import org.apache.hc.client5.http.impl.PrefixedIncrementingId;
 import org.apache.hc.client5.http.nio.AsyncClientConnectionManager;
@@ -57,6 +58,7 @@
 import org.apache.hc.core5.concurrent.ComplexFuture;
 import org.apache.hc.core5.concurrent.FutureCallback;
 import org.apache.hc.core5.function.Resolver;
+import org.apache.hc.core5.http.HttpConnection;
 import org.apache.hc.core5.http.HttpHost;
 import org.apache.hc.core5.http.HttpVersion;
 import org.apache.hc.core5.http.ProtocolVersion;
@@ -676,7 +678,7 @@ public void setValidateAfterInactivity(final TimeValue validateAfterInactivity)
 
     private static final PrefixedIncrementingId INCREMENTING_ID = new PrefixedIncrementingId("ep-");
 
-    static class InternalConnectionEndpoint extends AsyncConnectionEndpoint implements Identifiable {
+    static class InternalConnectionEndpoint extends AsyncConnectionEndpoint implements ConnectionHolder, Identifiable {
 
         private final AtomicReference<PoolEntry<HttpRoute, ManagedAsyncClientConnection>> poolEntryRef;
         private final String id;
@@ -773,6 +775,12 @@ public EndpointInfo getInfo() {
             return null;
         }
 
+        @Override
+        public HttpConnection get() {
+            final PoolEntry<HttpRoute, ManagedAsyncClientConnection> poolEntry = poolEntryRef.get();
+            return poolEntry != null ? poolEntry.getConnection() : null;
+        }
+
     }
 
     /**