ForkJoinTask与CompletableFuture [英] ForkJoinTask vs CompletableFuture

查看:353
本文介绍了ForkJoinTask与CompletableFuture的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java 8中,有两种启动异步计算的方式-CompletableFutureForkJoinTask.它们看起来都非常相似-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 

它也可以是RunnableAsynchronousCompletionTask

仅在旁注:ForkJoinTaskForkJoinPoolForkJoin...类是在1.7中添加的,而不是在1.8中添加的

Just on side note: ForkJoinTask, ForkJoinPool, ForkJoin... classes were added in 1.7 and not 1.8

这篇关于ForkJoinTask与CompletableFuture的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆