ForkJoinTask与CompletableFuture [英] ForkJoinTask vs CompletableFuture
问题描述
在Java 8中,有两种启动异步计算的方式-CompletableFuture
和ForkJoinTask
.它们看起来都非常相似-CompletableFuture
的内部类甚至扩展了ForkJoinTask
.
In Java 8 there are two ways of starting asynchronous computations - CompletableFuture
and ForkJoinTask
. They both seem fairly similar - the inner classes of CompletableFuture
even extend ForkJoinTask
.
是否有理由在一个之上使用另一个?
Is there a reason to use one over the other?
我可以看到的一个关键区别是CompletableFuture.join
方法只是阻塞直到将来完成(waitingGet
只是使用ManagedBlocker
旋转),而ForkJoinTask.join
可以将工作从队列中窃取以帮助您要完成的任务.
One key difference that I can see is that the CompletableFuture.join
method simply blocks until the future is complete (waitingGet
just spins using a ManagedBlocker
), whereas a ForkJoinTask.join
can steal work off the queue to help the task you're joining on to complete.
相对于另一种有好处吗?
Is there a benefit over one or the other?
推荐答案
它们是两件事,ForkJoinTask
是可以提交给ForkJoinPool
的任务,CompletableFuture
是可以与任何对象一起使用的承诺. Executor
,执行者不必是ForkJoinPool
They are two different things, ForkJoinTask
is a task that can be submitted to a ForkJoinPool
, CompletableFuture
is a promise that can work with any Executor
and the executor doesn't need to be the ForkJoinPool
,
这是事实,但是,例如,如果您未指定任何通用名称,则默认为ForkJoinPool
:
It is true however that the common ForkJoinPool
is the default if you don't specify any, for ex:
CompletableFuture.supplyAsync(()-> supplier);
如果您未通过Executor
,则
使用ForkJoinPool
.还有另一个overload
需要一个Executor
.
uses the ForkJoinPool
if you don't pass an Executor
. There is another overload
that takes an Executor
.
CompletableFuture.supplyAsync(()-> supplier,executor);
Async
,它是CompletableFuture
中的static
类,扩展了ForkJoinTask<Void>
,但根据Async
Async
,which is a static
class in CompletableFuture
extends ForkJoinTask<Void>
, but it doesn't need to be a ForkJoinTask
, from the docs of Async
/**基类可以充当FJ或普通Runnable */
/** Base class can act as either FJ or plain Runnable */
abstract static class Async extends ForkJoinTask<Void>
implements Runnable, AsynchronousCompletionTask
它也可以是Runnable
和AsynchronousCompletionTask
仅在旁注:ForkJoinTask
,ForkJoinPool
,ForkJoin...
类是在1.7中添加的,而不是在1.8中添加的
Just on side note: ForkJoinTask
, ForkJoinPool
, ForkJoin...
classes were added in 1.7 and not 1.8
这篇关于ForkJoinTask与CompletableFuture的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!