javaasynchronouscompletable-future

Is CompletableFuture run on different cores?


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

Solution

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