ForkJoinTask vs CompletableFuture

In Java 8, there are two ways to start asynchronous computing - CompletableFuture and ForkJoinTask . Both of them seem pretty similar - the CompletableFuture inner classes even extend ForkJoinTask .

Is there a reason to use one over the other?

One of the key differences that I see is that the CompletableFuture.join method just blocks until the future is complete ( waitingGet just rotates with the ManagedBlocker ), while ForkJoinTask.join can steal the work from the queue to help the task. which you are joining to complete.

Is there an advantage over this or that?

+6
source share
2 answers

These are two different things, ForkJoinTask is a task that can be sent to ForkJoinPool , CompletableFuture is a promise that can work with any Executor , and the executor should not be ForkJoinPool .

True, a generic ForkJoinPool is the default unless you specify it, for example:

 CompletableFuture.supplyAsync(()-> supplier); 

uses ForkJoinPool if you do not pass Executor . There is another overload that accepts Executor .

 CompletableFuture.supplyAsync(()-> supplier,executor); 

Async , which is the static class in CompletableFuture extends ForkJoinTask<Void> , but it should not be ForkJoinTask , from Async docs

/ ** Base class can act like FJ or regular Runnable * /

 abstract static class Async extends ForkJoinTask<Void> implements Runnable, AsynchronousCompletionTask 

It can also be Runnable and a AsynchronousCompletionTask

Only on the side of the note: ForkJoinTask , ForkJoinPool , ForkJoin... classes were added in 1.7, not 1.8

+3
source

I would say that ForkJoinTask more recommended when you have a big task, and want to split it into parallel execution of several subtasks. The ForkJoin uses a job theft algorithm that will efficiently use threads. CompletableFutures , on the other hand, is more suitable for a reactive programming model where you can create execution pipelines in synchronization or asynchrony mode and better control threads using thread pools in the executing service.

+1
source

All Articles