Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
/*
* Copyright (c) 2026 AsyncHttpClient Project. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.asynchttpclient.bench;

import io.netty.channel.Channel;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultChannelPromise;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.EventExecutor;
import org.asynchttpclient.AsyncCompletionHandler;
import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.Request;
import org.asynchttpclient.RequestBuilder;
import org.asynchttpclient.Response;
import org.asynchttpclient.channel.ChannelPoolPartitioning.PerHostChannelPoolPartitioning;
import org.asynchttpclient.netty.NettyResponseFuture;
import org.asynchttpclient.netty.channel.ConnectionSemaphore;
import org.asynchttpclient.netty.channel.NoopConnectionSemaphore;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
* The connection-permit bookkeeping a new connection pays with the default unlimited limits, where the
* semaphore is {@link NoopConnectionSemaphore}. {@code noopPermit} mirrors what that path did:
* {@code NettyRequestSender.isOnEventLoop} walking an event loop group from the caller thread,
* {@code acquirePartitionLockLazily}, and {@code NettyConnectListener.onSuccess} taking the key, allocating
* the permit holder and two release callbacks, setting the channel attribute and adding the close listener,
* which runs when the connection closes. {@code noPermit} is the same connection without a semaphore.
* Both build the response future and a fresh close future, which every new connection has anyway.
*/
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class ConnectionPermitBenchmark {

private static final AttributeKey<Runnable> PERMIT_RELEASE = AttributeKey.valueOf("permitRelease");

/** Event loops in the client's group; the default is twice the available processors. */
@Param({"8", "32"})
public int eventLoops;

private EventLoopGroup group;
private Channel channel;
private Request request;
private AsyncHandler<Object> handler;
private final ConnectionSemaphore noop = new NoopConnectionSemaphore();

@Setup(Level.Trial)
public void setup() {
group = new NioEventLoopGroup(eventLoops);
channel = new EmbeddedChannel();
request = new RequestBuilder().setUrl("http://api.example.com/v1/items").build();
handler = new AsyncCompletionHandler<Object>() {
@Override
public Object onCompleted(Response response) {
return null;
}
};
}

@TearDown(Level.Trial)
public void tearDown() {
channel.close();
group.shutdownGracefully(0, 0, TimeUnit.SECONDS).syncUninterruptibly();
}

@Benchmark
public Object noopPermit() throws IOException {
NettyResponseFuture<Object> future = newFuture(noop);
future.acquirePartitionLockLazily(isOnEventLoop());

ConnectionSemaphore semaphore = noop;
Object partitionKeyLock = future.takePartitionKeyLock();
AtomicReference<Object> permit = new AtomicReference<>(partitionKeyLock);
ChannelPromise closeFuture = new DefaultChannelPromise(channel);
if (partitionKeyLock != null) {
channel.attr(PERMIT_RELEASE).set(() -> releasePermitOnce(semaphore, permit));
closeFuture.addListener(f -> releasePermitOnce(semaphore, permit));
}
closeFuture.setSuccess();
return future;
}

@Benchmark
public Object noPermit() throws IOException {
NettyResponseFuture<Object> future = newFuture(null);
ChannelPromise closeFuture = new DefaultChannelPromise(channel);
closeFuture.setSuccess();
return future;
}

/** The group walk alone, as a caller thread pays it: no loop matches, so every one is visited. */
@Benchmark
public boolean isOnEventLoop() {
for (EventExecutor executor : group) {
if (executor.inEventLoop()) {
return true;
}
}
return false;
}

private NettyResponseFuture<Object> newFuture(ConnectionSemaphore semaphore) {
return new NettyResponseFuture<>(request, handler, null, 0, PerHostChannelPoolPartitioning.INSTANCE, semaphore, null);
}

private static void releasePermitOnce(ConnectionSemaphore semaphore, AtomicReference<Object> permit) {
Object partitionKeyLock = permit.getAndSet(null);
if (partitionKeyLock != null) {
semaphore.releaseChannelLock(partitionKeyLock);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public void onSuccess(Channel channel, InetSocketAddress remoteAddress) {
// request's object graph for the lifetime of a long-lived (HTTP/2) connection.
final ConnectionSemaphore semaphore = connectionSemaphore;
final Object partitionKeyLock = semaphore != null ? future.takePartitionKeyLock() : null;
final AtomicReference<Object> permit = new AtomicReference<>(partitionKeyLock);
final AtomicReference<Object> permit = partitionKeyLock != null ? new AtomicReference<>(partitionKeyLock) : null;
if (partitionKeyLock != null) {
// Also reachable from the channel, so an abort can return the permit before it tells the handler.
Channels.setPermitRelease(channel, () -> releasePermitOnce(semaphore, permit));
Expand Down Expand Up @@ -332,6 +332,9 @@ protected void onFailure(Throwable cause) {
* prune a live entry from the per-host map.
*/
private static void releasePermitOnce(ConnectionSemaphore semaphore, AtomicReference<Object> permit) {
if (permit == null) {
return;
}
Object partitionKeyLock = permit.getAndSet(null);
if (partitionKeyLock != null && semaphore != null) {
semaphore.releaseChannelLock(partitionKeyLock);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
import org.asynchttpclient.netty.channel.LeastConnectionsAddressSelector;
import org.asynchttpclient.netty.channel.NettyChannelConnector;
import org.asynchttpclient.netty.channel.NettyConnectListener;
import org.asynchttpclient.netty.channel.NoopConnectionSemaphore;
import org.asynchttpclient.netty.channel.RoundRobinAddressSelector;
import org.asynchttpclient.netty.channel.RoundRobinPartitionKey;
import org.asynchttpclient.netty.handler.Http2ContentDecompressor;
Expand Down Expand Up @@ -135,7 +136,8 @@ public final class NettyRequestSender {

private final AsyncHttpClientConfig config;
private final ChannelManager channelManager;
private final ConnectionSemaphore connectionSemaphore;
// Null when the limit is the built-in no-op: a new connection then takes and binds no permit.
private final @Nullable ConnectionSemaphore connectionSemaphore;
private final Timer nettyTimer;
private final AsyncHttpClientState clientState;
private final NettyRequestFactory requestFactory;
Expand All @@ -149,9 +151,7 @@ public final class NettyRequestSender {
public NettyRequestSender(AsyncHttpClientConfig config, ChannelManager channelManager, Timer nettyTimer, AsyncHttpClientState clientState) {
this.config = config;
this.channelManager = channelManager;
connectionSemaphore = config.getConnectionSemaphoreFactory() == null
? new DefaultConnectionSemaphoreFactory().newConnectionSemaphore(config)
: config.getConnectionSemaphoreFactory().newConnectionSemaphore(config);
connectionSemaphore = newConnectionSemaphore(config);
this.nettyTimer = nettyTimer;
this.clientState = clientState;
requestFactory = new NettyRequestFactory(config);
Expand Down Expand Up @@ -621,7 +621,9 @@ private <T> ListenableFuture<T> sendRequestWithNewChannel(Request request, Proxy
// acquireFreeChannelTimeout would stall every other connection it serves (and the permit
// may be released only by a task queued on this same loop). Off the loop — the initial
// execute() on the caller thread — keep the configured blocking wait.
future.acquirePartitionLockLazily(isOnEventLoop());
if (connectionSemaphore != null) {
future.acquirePartitionLockLazily(isOnEventLoop());
}
} catch (IOException semaphoreException) {
// The per-host permit is exhausted, but a sibling request may be establishing an HTTP/2
// connection to this origin we can multiplex onto (stream reuse needs no permit). Reuse one
Expand Down Expand Up @@ -1749,6 +1751,14 @@ private Channel pollHttp2(Object h2Key) {
return h2Channel;
}

static @Nullable ConnectionSemaphore newConnectionSemaphore(AsyncHttpClientConfig config) {
ConnectionSemaphore semaphore = config.getConnectionSemaphoreFactory() == null
? new DefaultConnectionSemaphoreFactory().newConnectionSemaphore(config)
: config.getConnectionSemaphoreFactory().newConnectionSemaphore(config);
// Exactly the built-in class: a subclass may override acquire or release.
return semaphore.getClass() == NoopConnectionSemaphore.class ? null : semaphore;
}

private boolean isOnEventLoop() {
for (EventExecutor executor : channelManager.getEventLoopGroup()) {
if (executor.inEventLoop()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.ssl.NotSslRecordException;
import io.netty.util.AttributeKey;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;
import org.asynchttpclient.AsyncCompletionHandler;
Expand Down Expand Up @@ -47,6 +48,7 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
Expand Down Expand Up @@ -390,4 +392,45 @@ void thePermitIsReleasedExactlyOnce() throws Exception {
}
}

/**
* Without a semaphore (unlimited connections) a new connection takes no permit and binds no release.
*/
@Test
void noSemaphoreBindsNoPermitRelease() throws Exception {
NettyResponseFuture<Object> future = newFuture(HTTPS_URL, null, noopHandler());
future.acquirePartitionLockLazily();
assertNull(future.takePartitionKeyLock(), "sanity: no permit was taken");

NettyConnectListener<Object> listener = new NettyConnectListener<>(future, null, channelManager, null);
EmbeddedChannel channel = new EmbeddedChannel();
try {
listener.onSuccess(channel, new InetSocketAddress("127.0.0.1", 12345));
assertFalse(channel.hasAttr(AttributeKey.valueOf("permitRelease")));
Channels.releasePermit(channel);
channel.close().sync();
} finally {
channel.finishAndReleaseAll();
}
}

@Test
void aFiniteSemaphoreBindsThePermitReleaseToTheChannel() throws Exception {
CountingSemaphore semaphore = new CountingSemaphore(new PerHostConnectionSemaphore(1, 0));
NettyResponseFuture<Object> future = newFuture(HTTPS_URL, semaphore, noopHandler());
future.acquirePartitionLockLazily();

NettyConnectListener<Object> listener = new NettyConnectListener<>(future, null, channelManager, semaphore);
EmbeddedChannel channel = new EmbeddedChannel();
try {
listener.onSuccess(channel, new InetSocketAddress("127.0.0.1", 12345));
assertTrue(channel.hasAttr(AttributeKey.valueOf("permitRelease")));

Channels.releasePermit(channel);
assertEquals(1, semaphore.releases.get());
channel.close().sync();
assertEquals(1, semaphore.releases.get(), "the close listener must not release a second time");
} finally {
channel.finishAndReleaseAll();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* Copyright (c) 2026 AsyncHttpClient Project. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.asynchttpclient.netty.request;

import org.asynchttpclient.netty.channel.CombinedConnectionSemaphore;
import org.asynchttpclient.netty.channel.ConnectionSemaphore;
import org.asynchttpclient.netty.channel.MaxConnectionSemaphore;
import org.asynchttpclient.netty.channel.NoopConnectionSemaphore;
import org.junit.jupiter.api.Test;

import static org.asynchttpclient.Dsl.config;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;

class NettyRequestSenderConnectionSemaphoreTest {

@Test
void unlimitedDefaultTakesNoPermits() {
assertNull(NettyRequestSender.newConnectionSemaphore(config().build()));
}

@Test
void finiteLimitsKeepTheirSemaphore() {
assertInstanceOf(MaxConnectionSemaphore.class,
NettyRequestSender.newConnectionSemaphore(config().setMaxConnections(10).build()));
assertInstanceOf(CombinedConnectionSemaphore.class,
NettyRequestSender.newConnectionSemaphore(config().setMaxConnectionsPerHost(2).build()));
}

@Test
void aCustomFactoryKeepsItsSemaphore() {
ConnectionSemaphore custom = new ConnectionSemaphore() {
@Override
public void acquireChannelLock(Object partitionKey) {
}

@Override
public void releaseChannelLock(Object partitionKey) {
}
};
assertSame(custom, NettyRequestSender.newConnectionSemaphore(
config().setConnectionSemaphoreFactory(c -> custom).build()));
}

@Test
void aNoopSubclassKeepsItsSemaphore() {
ConnectionSemaphore subclass = new NoopConnectionSemaphore() {
@Override
public void releaseChannelLock(Object partitionKey) {
}
};
assertSame(subclass, NettyRequestSender.newConnectionSemaphore(
config().setConnectionSemaphoreFactory(c -> subclass).build()));
}
}
Loading