Reputation: 467
How to limit the number of connection/request for java.net.http.HttpClient?
I see I can set an Executor to HttpClient but I don't know: if I limit the number of thread in pool of Executor, is it limit also the number of connection?
Another way to limit the number of connection?
Upvotes: 4
Views: 3442
Reputation: 1504
The HTTP/1.1 connection pool size is controlled by the jdk.httpclient.connectionPoolSize system property. If unset it defaults to unlimited connections.
Upvotes: 1
Reputation: 3288
To limit the number of concurrent requests made through the HttpClient you will have to do so at the application level. The HttpClient is purely asynchronous so limiting the number of threads in the HttpClient executor will not work. Similarly, limiting the number of connections in the keep-alive pool will not work, since the pool contains only idle connections.
It should be very easy to limit the number of concurrent requests at the application level by guarding the code that sends requests with a simple semaphore (see java.util.concurrent.Semaphore). To limit the number of concurrent requests to e.g. 10 requests, just create a semaphore with 10 permits, acquire the semaphore before sending a request and release it when the response has arrived.
Upvotes: 5