Is CompletableFuture run on different cores?

125 views Asked by At

When one uses CompletableFuture with Executor. Are these tasks run on different cores. Or it could it be the same core but just Threads from Theadpool? In the documentation I can't read anything about it . This task will be run in a for loop creating 10 tasks. Will these run on different cores . How can I check this ? Thanks

Executor testExecutor = Executors.newFixedThreadPool(5);
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> "Baeldung",testExecutor);   
2

There are 2 answers

7
BoppreH On BEST ANSWER

Yes, threads usually run on separate cores. Note that you can still only have one thread active per core (with minor exceptions for hyper-threading), so if you're doing heavy CPU processing you shouldn't create more threads than your number of cores.

There's also some overhead switching between threads, so avoid creating too many threads even if they're IO bound. The thread pool you're using is a good way to manage that.

You are probably not finding many resources on this because thread management is a responsibility of the operating system, and not the language runtime.

I'm not aware of any easy way to check which core a thread is using, but you can always use your task manager to check how your process is distributed.

7
jbx On

It depends on the size of the thread pool, how many other threads you have running, how many other processes are competing for resources on the same machine, and how many CPU cores (or hyperthreading virtual cores) you have. There is no guarantee that they will be on different cores. Thread scheduling is controlled by the OS kernel, which usually switches context at strategic points, such as blocking I/O calls, or when where it deems some CPU cycles should be dedicated to a waiting thread.

As a side-note, from Java 21 onwards, you now also have virtual threads, which are handled by the JVM, and the OS would not even be aware of them. Multiple virtual threads would still run on one or more platform threads which the OS would schedule and parallelize (potentially on multiple cores), but the virtual threads themselves would be scheduled by the JVM.