ForkJoinTask与CompletableFuture

编程入门 行业动态 更新时间:2024-10-10 15:18:09
本文介绍了ForkJoinTask与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

本文发布于:2023-11-25 20:18:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631207.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ForkJoinTask   CompletableFuture

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!