HttpClient has no explicit way of releasing threads

Daniel Fuchs daniel.fuchs at oracle.com
Tue May 10 13:53:28 UTC 2022


On 10/05/2022 14:39, Remi Forax wrote:
>> This is not a big problem but I have seen peaks with suddenly many, many
>> threads (in test code) where many HttpClients were created for single use
>> and I was wondering if it was ever considered to add a method for disposing
>> the threads explicitly?
> You can change the Executor (it's one parameter of the builder) to use whatever executors you want so you can shutdown that executor as you want.
> This should fixed (1).
> 
> Also once you update to Java 19/21, it seems a good scenario to test the executor that spawn virtual threads instead of platform threads.
> 

Some word of caution about shutting down the executor:
If you know that the client is no longer used, and there are
no requests in progress, what Rémi suggests should be fine.
Otherwise shutting down the executor when the client is still
in use could lead to undefined behaviour, including not
being able to complete the CompletableFutures that have
been returned by `sendAsync` - or which `send` calls have
joined.

This has been fixed in JDK 19 by JDK-8277969, but otherwise,
and especially on previous versions of the JDK, you should
make sure that all operations have terminated before shutting
down the executor (even gracefully).

Using virtual threads should be fine - as long as they are not
pooled :-)

best regards,

-- daniel


More information about the core-libs-dev mailing list