Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit connections for java.net.http.HttpClient

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?

like image 999
lecogiteur Avatar asked Oct 22 '25 15:10

lecogiteur


1 Answers

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.

like image 134
daniel Avatar answered Oct 25 '25 04:10

daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!