Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 796
lorenzocastillo Avatar asked Jul 31 '17 20:07

lorenzocastillo


2 Answers

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).

like image 71
Kayaman Avatar answered Oct 13 '22 01:10

Kayaman


If you schedule your computation without specifying a thread-pool, the fork-join common pool would be used, otherwise you can specify your own Executor to supplyAsync and choose a size that fits your need.

like image 41
Sleiman Jneidi Avatar answered Oct 12 '22 23:10

Sleiman Jneidi