Search code examples
javamultithreadingconcurrencycompletable-future

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


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?


Solution

  • As is 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 threadpool is used, either implicitly (unless you have a single core machine in which case the threads aren't pooled) or explicitly. In your case you would get to control the amount of threads used by using an explicit Executor (e.g. ThreadPoolExecutor) with the amount of threads you want (most likely a lot less than 1000).

    The calls cannot share a single thread (the calling thread), as Java doesn't have the capability for what people these days understand by asynchronous due to the popular async/await paradigm (i.e. the fictional "truly asynchronous" term - synchronous vs. asynchronous is independent of threads, but asynchronicity can be implemented with threads, as it is done in CompletableFuture).

    With the HttpClient introduced in Java 11 (as incubator module in 9), it's possible to perform asynchronous requests with a threadpool using CompletableFutures in the "standard" way. If you're looking to minimize the thread count, you'll have to switch to reactive programming and use something like Spring's WebClient for the requests.