You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@hc.apache.org by "arturobernalg (via GitHub)" <gi...@apache.org> on 2026/01/06 16:55:18 UTC
[PR] Implement shared FIFO execution queue for H2 client [httpcomponents-client]
arturobernalg opened a new pull request, #776:
URL: https://github.com/apache/httpcomponents-client/pull/776
Add a shared FIFO execution queue to cap concurrently executing async requests per client instance. Queue overflow requests and execute them when in-flight execution completes. Ensure queue slots are released on all terminal paths, including synchronous start failures.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For additional commands, e-mail: dev-help@hc.apache.org
Re: [PR] Implement shared FIFO execution queue for Async/H2 client [httpcomponents-client]
Posted by "ok2c (via GitHub)" <gi...@apache.org>.
ok2c commented on PR #776:
URL: https://github.com/apache/httpcomponents-client/pull/776#issuecomment-4365923123
@arturobernalg You overlooked one my comment about `AtomicReference`. Looks good otherwise.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For additional commands, e-mail: dev-help@hc.apache.org
Re: [PR] Implement shared FIFO execution queue for Async/H2 client [httpcomponents-client]
Posted by "arturobernalg (via GitHub)" <gi...@apache.org>.
arturobernalg merged PR #776:
URL: https://github.com/apache/httpcomponents-client/pull/776
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For additional commands, e-mail: dev-help@hc.apache.org
Re: [PR] Implement shared FIFO execution queue for Async/H2 client [httpcomponents-client]
Posted by "ok2c (via GitHub)" <gi...@apache.org>.
ok2c commented on PR #776:
URL: https://github.com/apache/httpcomponents-client/pull/776#issuecomment-4368712735
@arturobernalg I think we may have overlooked one important detail. What is going to happen if the client gets shut down and there are still pending requests stuck in the execution queue. We need to make sure those requests get properly cancelled.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For additional commands, e-mail: dev-help@hc.apache.org
Re: [PR] Implement shared FIFO execution queue for Async/H2 client [httpcomponents-client]
Posted by "ok2c (via GitHub)" <gi...@apache.org>.
ok2c commented on code in PR #776:
URL: https://github.com/apache/httpcomponents-client/pull/776#discussion_r3177957497
##########
httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/SharedRequestExecutionQueue.java:
##########
@@ -0,0 +1,136 @@
+/*
+ * ====================================================================
+ * 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.async;
+
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
+
+import org.apache.hc.core5.annotation.Internal;
+import org.apache.hc.core5.concurrent.Cancellable;
+import org.apache.hc.core5.util.Args;
+
+/**
+ * Shared FIFO execution queue with a hard cap on concurrently executing tasks.
+ * Tasks beyond the cap are queued and executed when in-flight count drops.
+ */
+@Internal
+final class SharedRequestExecutionQueue {
+
+ private final int maxConcurrent;
+ private final AtomicInteger inFlight;
+ private final ConcurrentLinkedQueue<Entry> queue;
+ private final AtomicBoolean draining;
+
+ SharedRequestExecutionQueue(final int maxConcurrent) {
+ Args.positive(maxConcurrent, "maxConcurrent");
+ this.maxConcurrent = maxConcurrent;
+ this.inFlight = new AtomicInteger(0);
+ this.queue = new ConcurrentLinkedQueue<>();
+ this.draining = new AtomicBoolean(false);
+ }
+
+ Cancellable enqueue(final Runnable task, final Cancellable onCancel) {
+ Args.notNull(task, "task");
+ Args.notNull(onCancel, "onCancel");
+
+ final Entry entry = new Entry(task, onCancel);
+ queue.add(entry);
+ drain();
+ return entry;
+ }
+
+ void completed() {
+ inFlight.decrementAndGet();
+ drain();
+ }
+
+ private void drain() {
+ for (;;) {
+ if (!draining.compareAndSet(false, true)) {
+ return;
+ }
+ try {
+ while (inFlight.get() < maxConcurrent) {
+ final Entry entry = queue.poll();
+ if (entry == null) {
+ break;
+ }
+ if (!entry.tryStart()) {
+ continue;
+ }
+ inFlight.incrementAndGet();
+ entry.run();
+ }
+ } finally {
+ draining.set(false);
+ }
+ if (inFlight.get() >= maxConcurrent || queue.isEmpty()) {
+ return;
+ }
+ }
+ }
+
+
+ private static final class Entry implements Cancellable {
+
+ private static final int QUEUED = 0;
+ private static final int STARTED = 1;
+ private static final int CANCELLED = 2;
+
+ private static final AtomicIntegerFieldUpdater<Entry> STATE = AtomicIntegerFieldUpdater.newUpdater(Entry.class, "state");
+
+ private final Runnable task;
+ private final Cancellable onCancel;
+ private volatile int state;
Review Comment:
@arturobernalg Please use an enum and `AtomicReference` instead of an int and `AtomicIntegerFieldUpdater`. It will be simpler and more consistent with the rest of the library.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For additional commands, e-mail: dev-help@hc.apache.org
Re: [PR] Implement shared FIFO execution queue for Async/H2 client [httpcomponents-client]
Posted by "ok2c (via GitHub)" <gi...@apache.org>.
ok2c commented on code in PR #776:
URL: https://github.com/apache/httpcomponents-client/pull/776#discussion_r3173878361
##########
httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/SharedRequestExecutionQueue.java:
##########
@@ -0,0 +1,138 @@
+/*
+ * ====================================================================
+ * 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.async;
+
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
+
+import org.apache.hc.core5.annotation.Internal;
+import org.apache.hc.core5.concurrent.Cancellable;
+import org.apache.hc.core5.util.Args;
+
+/**
+ * Shared FIFO execution queue with a hard cap on concurrently executing tasks.
+ * Tasks beyond the cap are queued and executed when in-flight count drops.
+ */
+@Internal
+final class SharedRequestExecutionQueue {
+
+ private final int maxConcurrent;
+ private final AtomicInteger inFlight;
+ private final ConcurrentLinkedQueue<Entry> queue;
+ private final AtomicBoolean draining;
+
+ SharedRequestExecutionQueue(final int maxConcurrent) {
+ if (maxConcurrent <= 0) {
+ throw new IllegalArgumentException("maxConcurrent must be > 0");
+ }
+ this.maxConcurrent = maxConcurrent;
+ this.inFlight = new AtomicInteger(0);
+ this.queue = new ConcurrentLinkedQueue<>();
+ this.draining = new AtomicBoolean(false);
+ }
+
+ Cancellable enqueue(final Runnable task, final Runnable onCancel) {
Review Comment:
@arturobernalg Why not using `Cancellable` here instead of `Runnable`? Would not that be clearer?
##########
httpclient5/src/test/java/org/apache/hc/client5/http/examples/H2SharedClientQueueLocalExample.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * ====================================================================
+ * 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.examples;
+
+import java.net.InetSocketAddress;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+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.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.client5.http.impl.async.H2AsyncClientBuilder;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.Message;
+import org.apache.hc.core5.http.URIScheme;
+import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer;
+import org.apache.hc.core5.http.message.StatusLine;
+import org.apache.hc.core5.http.nio.AsyncRequestConsumer;
+import org.apache.hc.core5.http.nio.AsyncServerRequestHandler;
+import org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer;
+import org.apache.hc.core5.http.nio.support.AsyncResponseBuilder;
+import org.apache.hc.core5.http.nio.support.BasicRequestConsumer;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.http.protocol.HttpCoreContext;
+import org.apache.hc.core5.http2.HttpVersionPolicy;
+import org.apache.hc.core5.http2.config.H2Config;
+import org.apache.hc.core5.http2.impl.nio.bootstrap.H2ServerBootstrap;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+import org.apache.hc.core5.reactor.ListenerEndpoint;
+
+
+/**
+ * Demonstrates client-level request throttling for the HTTP/2 async client using a shared FIFO queue.
+ * <p>
+ * The example configures {@link org.apache.hc.client5.http.impl.async.H2AsyncClientBuilder#setMaxQueuedRequests(int)}
+ * to cap the number of concurrently executing requests per client instance. Requests submitted beyond that limit are
+ * queued in FIFO order and executed as soon as the number of in-flight requests drops below the configured maximum.
+ * <p>
+ * A local HTTP/2 server is started with a permissive {@code maxConcurrentStreams} setting so that the client-side cap
+ * is the limiting factor. The example then submits multiple requests and prints summary statistics, including the
+ * maximum number of concurrent server requests observed.
+ *
+ * @since 5.7
+ */
+public final class H2SharedClientQueueLocalExample {
+
+
+ public static void main(final String[] args) throws Exception {
+ final int maxConcurrentPerClient = 2; // <-- the feature under test
+ final int totalRequests = 50;
+
+ final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
+ .setIoThreadCount(1)
+ .build();
+
+ final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
+
+ final AtomicInteger serverInFlight = new AtomicInteger(0);
+ final AtomicInteger serverMaxInFlight = new AtomicInteger(0);
+
+ final H2Config serverH2Config = H2Config.custom()
+ .setPushEnabled(false)
+ // Keep server permissive. We want the *client* cap to be the limiting factor.
+ .setMaxConcurrentStreams(256)
+ .build();
+
+ final HttpAsyncServer server = H2ServerBootstrap.bootstrap()
Review Comment:
@arturobernalg Same here. Drop all server side code. Use `nghttp2.org`
##########
httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/SharedRequestExecutionQueue.java:
##########
@@ -0,0 +1,138 @@
+/*
+ * ====================================================================
+ * 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.async;
+
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
+
+import org.apache.hc.core5.annotation.Internal;
+import org.apache.hc.core5.concurrent.Cancellable;
+import org.apache.hc.core5.util.Args;
+
+/**
+ * Shared FIFO execution queue with a hard cap on concurrently executing tasks.
+ * Tasks beyond the cap are queued and executed when in-flight count drops.
+ */
+@Internal
+final class SharedRequestExecutionQueue {
+
+ private final int maxConcurrent;
+ private final AtomicInteger inFlight;
+ private final ConcurrentLinkedQueue<Entry> queue;
+ private final AtomicBoolean draining;
+
+ SharedRequestExecutionQueue(final int maxConcurrent) {
+ if (maxConcurrent <= 0) {
Review Comment:
@arturobernalg Please use `Args` here as well for consistency.
##########
httpclient5/src/test/java/org/apache/hc/client5/http/examples/AsyncSharedClientQueueExample.java:
##########
@@ -0,0 +1,149 @@
+/*
+ * ====================================================================
+ * 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.examples;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+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.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.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.message.StatusLine;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+
+/**
+ * Demonstrates client-level request throttling for the async client using a shared FIFO queue.
+ * <p>
+ * The example configures {@code setMaxQueuedRequests(int)} to limit how many requests may execute concurrently for
+ * this client instance. Requests submitted beyond that limit are held in a shared FIFO queue and executed later.
+ * <p>
+ * This example assumes the target server endpoint is slow enough for several requests to overlap. No local server is
+ * started here; examples are intended to demonstrate API usage, not to act as integration tests.
+ *
+ * @since 5.7
+ */
+public final class AsyncSharedClientQueueExample {
Review Comment:
@arturobernalg Drop all non-essentials for the examples. Examples do not need to be fully functional. Just clear and concise.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For additional commands, e-mail: dev-help@hc.apache.org
Re: [PR] Implement shared FIFO execution queue for Async/H2 client [httpcomponents-client]
Posted by "arturobernalg (via GitHub)" <gi...@apache.org>.
arturobernalg commented on PR #776:
URL: https://github.com/apache/httpcomponents-client/pull/776#issuecomment-4346074612
> @arturobernalg Lookd good overall.
@ok2c please do one last pass
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For additional commands, e-mail: dev-help@hc.apache.org
Re: [PR] Implement shared FIFO execution queue for Async/H2 client [httpcomponents-client]
Posted by "ok2c (via GitHub)" <gi...@apache.org>.
ok2c commented on PR #776:
URL: https://github.com/apache/httpcomponents-client/pull/776#issuecomment-4186773439
@arturobernalg Please rebase this change-set whenever you have a minute
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For additional commands, e-mail: dev-help@hc.apache.org
Re: [PR] Implement shared FIFO execution queue for Async/H2 client [httpcomponents-client]
Posted by "arturobernalg (via GitHub)" <gi...@apache.org>.
arturobernalg commented on PR #776:
URL: https://github.com/apache/httpcomponents-client/pull/776#issuecomment-4197216861
> @arturobernalg Please rebase this change-set whenever you have a minute
@ok2c done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For additional commands, e-mail: dev-help@hc.apache.org
Re: [PR] Implement shared FIFO execution queue for Async/H2 client [httpcomponents-client]
Posted by "arturobernalg (via GitHub)" <gi...@apache.org>.
arturobernalg commented on PR #776:
URL: https://github.com/apache/httpcomponents-client/pull/776#issuecomment-4368931567
> @arturobernalg I think we may have overlooked one important detail. What is going to happen if the client gets shut down and there are still pending requests stuck in the execution queue. We need to make sure those requests get properly cancelled.
@ok2c
I added a close path to the shared execution queue and close it from the async client shutdown path. Pending queued exchanges are now cancelled instead of being left stuck in the queue.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For additional commands, e-mail: dev-help@hc.apache.org
Re: [PR] Implement shared FIFO execution queue for Async/H2 client [httpcomponents-client]
Posted by "arturobernalg (via GitHub)" <gi...@apache.org>.
arturobernalg commented on code in PR #776:
URL: https://github.com/apache/httpcomponents-client/pull/776#discussion_r3178162312
##########
httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/SharedRequestExecutionQueue.java:
##########
@@ -0,0 +1,136 @@
+/*
+ * ====================================================================
+ * 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.async;
+
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
+
+import org.apache.hc.core5.annotation.Internal;
+import org.apache.hc.core5.concurrent.Cancellable;
+import org.apache.hc.core5.util.Args;
+
+/**
+ * Shared FIFO execution queue with a hard cap on concurrently executing tasks.
+ * Tasks beyond the cap are queued and executed when in-flight count drops.
+ */
+@Internal
+final class SharedRequestExecutionQueue {
+
+ private final int maxConcurrent;
+ private final AtomicInteger inFlight;
+ private final ConcurrentLinkedQueue<Entry> queue;
+ private final AtomicBoolean draining;
+
+ SharedRequestExecutionQueue(final int maxConcurrent) {
+ Args.positive(maxConcurrent, "maxConcurrent");
+ this.maxConcurrent = maxConcurrent;
+ this.inFlight = new AtomicInteger(0);
+ this.queue = new ConcurrentLinkedQueue<>();
+ this.draining = new AtomicBoolean(false);
+ }
+
+ Cancellable enqueue(final Runnable task, final Cancellable onCancel) {
+ Args.notNull(task, "task");
+ Args.notNull(onCancel, "onCancel");
+
+ final Entry entry = new Entry(task, onCancel);
+ queue.add(entry);
+ drain();
+ return entry;
+ }
+
+ void completed() {
+ inFlight.decrementAndGet();
+ drain();
+ }
+
+ private void drain() {
+ for (;;) {
+ if (!draining.compareAndSet(false, true)) {
+ return;
+ }
+ try {
+ while (inFlight.get() < maxConcurrent) {
+ final Entry entry = queue.poll();
+ if (entry == null) {
+ break;
+ }
+ if (!entry.tryStart()) {
+ continue;
+ }
+ inFlight.incrementAndGet();
+ entry.run();
+ }
+ } finally {
+ draining.set(false);
+ }
+ if (inFlight.get() >= maxConcurrent || queue.isEmpty()) {
+ return;
+ }
+ }
+ }
+
+
+ private static final class Entry implements Cancellable {
+
+ private static final int QUEUED = 0;
+ private static final int STARTED = 1;
+ private static final int CANCELLED = 2;
+
+ private static final AtomicIntegerFieldUpdater<Entry> STATE = AtomicIntegerFieldUpdater.newUpdater(Entry.class, "state");
+
+ private final Runnable task;
+ private final Cancellable onCancel;
+ private volatile int state;
Review Comment:
@ok2c done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For additional commands, e-mail: dev-help@hc.apache.org
Re: [PR] Implement shared FIFO execution queue for Async/H2 client [httpcomponents-client]
Posted by "ok2c (via GitHub)" <gi...@apache.org>.
ok2c commented on code in PR #776:
URL: https://github.com/apache/httpcomponents-client/pull/776#discussion_r3187159119
##########
httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/SharedRequestExecutionQueue.java:
##########
@@ -0,0 +1,173 @@
+/*
+ * ====================================================================
+ * 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.async;
+
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
+
+import org.apache.hc.core5.annotation.Internal;
+import org.apache.hc.core5.concurrent.Cancellable;
+import org.apache.hc.core5.util.Args;
+
+/**
+ * Shared FIFO execution queue with a cap on concurrently executing requests.
+ */
+@Internal
+final class SharedRequestExecutionQueue {
+
+ private final int maxConcurrent;
+ private final AtomicInteger inFlight;
+ private final ConcurrentLinkedQueue<Entry> queue;
+ private final AtomicBoolean draining;
+ private final AtomicBoolean closed;
+
+ SharedRequestExecutionQueue(final int maxConcurrent) {
+ this.maxConcurrent = Args.positive(maxConcurrent, "Max concurrent requests");
+ this.inFlight = new AtomicInteger();
+ this.queue = new ConcurrentLinkedQueue<>();
+ this.draining = new AtomicBoolean();
+ this.closed = new AtomicBoolean();
+ }
+
+ Cancellable enqueue(final Runnable task, final Runnable onCancel) {
+ Args.notNull(task, "Task");
+ Args.notNull(onCancel, "Cancel callback");
+
+ final Entry entry = new Entry(task, onCancel);
+
+ if (closed.get()) {
+ entry.cancel();
+ return entry;
+ }
+
+ queue.add(entry);
+
+ if (closed.get()) {
+ cancelPending();
+ return entry;
+ }
+
+ drain();
+ return entry;
+ }
+
+ void completed() {
+ inFlight.decrementAndGet();
+ if (closed.get()) {
+ cancelPending();
+ } else {
+ drain();
+ }
+ }
+
+ void close() {
+ if (closed.compareAndSet(false, true)) {
+ cancelPending();
+ }
+ }
+
+ private void cancelPending() {
+ Entry entry;
+ while ((entry = queue.poll()) != null) {
+ entry.cancel();
+ }
+ }
+
+ private void drain() {
+ for (;;) {
+ if (!draining.compareAndSet(false, true)) {
+ return;
+ }
+ try {
+ while (!closed.get() && inFlight.get() < maxConcurrent) {
+ final Entry entry = queue.poll();
+ if (entry == null) {
+ break;
+ }
+ if (closed.get()) {
+ entry.cancel();
+ continue;
+ }
+ if (!entry.tryStart()) {
+ continue;
+ }
+ inFlight.incrementAndGet();
+ entry.run();
+ }
+ } finally {
+ draining.set(false);
+ }
+
+ if (closed.get() || inFlight.get() >= maxConcurrent || queue.isEmpty()) {
+ return;
+ }
+ }
+ }
+
+ private static final class Entry implements Cancellable {
+
+ private static final int QUEUED = 0;
+ private static final int STARTED = 1;
+ private static final int CANCELLED = 2;
+
+ private static final AtomicIntegerFieldUpdater<Entry> STATE_UPDATER =
Review Comment:
@arturobernalg Is there a reason you reverted your implementation back to `AtomicIntegerFieldUpdater`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For additional commands, e-mail: dev-help@hc.apache.org
Re: [PR] Implement shared FIFO execution queue for Async/H2 client [httpcomponents-client]
Posted by "ok2c (via GitHub)" <gi...@apache.org>.
ok2c commented on code in PR #776:
URL: https://github.com/apache/httpcomponents-client/pull/776#discussion_r3143775399
##########
httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalHttpAsyncExecRuntime.java:
##########
@@ -407,6 +373,39 @@ public void cancelled() {
}
}
+ @Override
+ public Cancellable execute(
+ final String id,
+ final AsyncClientExchangeHandler exchangeHandler,
+ final HttpClientContext context) {
+
+ if (executionQueue == null) {
+ return startExecution(id, exchangeHandler, context);
+ }
+
+ final ComplexCancellable complexCancellable = new ComplexCancellable();
+
+ final Cancellable queued = executionQueue.enqueue(
+ () -> {
+ final AsyncClientExchangeHandler wrapped =
+ new ReleasingAsyncClientExchangeHandler(exchangeHandler, executionQueue::completed);
+ try {
+ final Cancellable cancellable = startExecution(id, wrapped, context);
+ complexCancellable.setDependency(cancellable);
+ } catch (final RuntimeException ex) {
+ wrapped.failed(ex);
+ }
+ },
+ exchangeHandler::cancel);
+
+ return () -> {
Review Comment:
@arturobernalg Can be simplified as `complexCancellable.setDependency(queued)`
##########
httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2AsyncExecRuntime.java:
##########
@@ -261,41 +255,47 @@ public EndpointInfo getEndpointInfo() {
return null;
}
- private boolean tryAcquireSlot() {
- if (sharedQueued == null || maxQueued <= 0) {
- return true;
+ @Override
+ public Cancellable execute(
+ final String id,
+ final AsyncClientExchangeHandler exchangeHandler,
+ final HttpClientContext context) {
+
+ final Endpoint endpoint = ensureValid();
+ final ComplexCancellable complexCancellable = new ComplexCancellable();
+
+ if (executionQueue == null) {
+ startExecution(id, endpoint, exchangeHandler, context, complexCancellable);
+ return complexCancellable;
}
- for (;;) {
- final int q = sharedQueued.get();
- if (q >= maxQueued) {
- return false;
- }
- if (sharedQueued.compareAndSet(q, q + 1)) {
+
+ final Cancellable queued = executionQueue.enqueue(
+ () -> {
+ final AsyncClientExchangeHandler wrapped =
+ new ReleasingAsyncClientExchangeHandler(exchangeHandler, executionQueue::completed);
+ try {
+ startExecution(id, endpoint, wrapped, context, complexCancellable);
+ } catch (final RuntimeException ex) {
+ wrapped.failed(ex);
+ }
+ },
+ exchangeHandler::cancel);
+
+ return () -> {
Review Comment:
@arturobernalg Can be simplified as `complexCancellable.setDependency(queued)`
##########
httpclient5/src/test/java/org/apache/hc/client5/http/examples/AsyncSharedClientQueueLocalExample.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * ====================================================================
+ * 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.examples;
+
+import java.net.InetSocketAddress;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+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.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.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.Message;
+import org.apache.hc.core5.http.URIScheme;
+import org.apache.hc.core5.http.impl.bootstrap.AsyncServerBootstrap;
+import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer;
+import org.apache.hc.core5.http.message.StatusLine;
+import org.apache.hc.core5.http.nio.AsyncRequestConsumer;
+import org.apache.hc.core5.http.nio.AsyncServerRequestHandler;
+import org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer;
+import org.apache.hc.core5.http.nio.support.AsyncResponseBuilder;
+import org.apache.hc.core5.http.nio.support.BasicRequestConsumer;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.http.protocol.HttpCoreContext;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.reactor.IOReactorConfig;
+import org.apache.hc.core5.reactor.ListenerEndpoint;
+
+/**
+ * Demonstrates client-level request throttling for the async client using a shared FIFO queue.
+ * <p>
+ * The example configures {@code setMaxQueuedRequests(int)} to cap the number of concurrently executing requests per
+ * client instance. Requests submitted beyond that limit are queued in FIFO order and executed when the number of
+ * in-flight requests drops below the configured maximum.
+ *
+ * @since 5.7
+ */
+public final class AsyncSharedClientQueueLocalExample {
Review Comment:
@arturobernalg Examples are not integration tests. They do not need to be fully functional. They need to be informative and easy to understand. Drop the server side code. If there are any assumptions about the server side functionality, just put a comment about it
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@hc.apache.org
For additional commands, e-mail: dev-help@hc.apache.org