CompletableFuture multi-threaded, single thread concurrent, or both?

lorenzocastillo :

I just started looking into Java's CompletableFuture and a little bit confused on whether this is truly asynchronous (i.e running on one thread concurrently) or spanning multiple threads (Parallel).

For example, suppose I'd like to make 1000 different service calls. Suppose further that each service call can be made asynchronously. When using CompletableFuture, will the JVM make 1000 separate threads (assuming the JVM allows for this many threads), or execute all of these requests in one thread? Or is it doing a bit of both? Using some threads to execute those requests asynchronously?

What I want to do is something like this (in Python): https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html

is there a way to execute multiple requests/operations on the same thread in Java asynchronously?

Kayaman :

As clearly explained in the javadoc

All async methods without an explicit Executor argument are performed using the ForkJoinPool.commonPool() (unless it does not support a parallelism level of at least two, in which case, a new Thread is created to run each task).

So a pool is used, either implicitly or explicitly (well, unless you have a single core machine which is quite rare these days). I wouldn't recommend creating a pool of 1000 threads though.

If you want to use only a single thread for all those async calls, you can use Executors.newSingleThreadExecutor() and pass that as the parameter (just remember to use the same executor).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=465540&siteId=1