英文:
What is different between join/get and allOf in completable future?
问题
如果文档中提到的allOf
表示它是"CompletableFuture类的静态方法。当所有指定的CompletableFutures都完成时,它会返回一个新的CompletableFuture对象",而join
是"CompletableFuture类的静态方法。当所有指定的CompletableFutures都完成时,它会返回一个新的CompletableFuture对象",那么我为什么要同时使用它们?我能只使用allOf
吗?或者只使用join
吗?或者它们可以一起使用吗?
我的用例是我正在使用CompletableFuture异步调用n个任务,但我想将它们的结果组合在一起。
英文:
If allOf in the documentation indicates that it's " a static method of the CompletableFuture class. It returns a new CompletableFuture object when all of the specified CompletableFutures are complete" and join is " a static method of the CompletableFuture class. It returns a new CompletableFuture object when all of the specified CompletableFutures are complete" so why should I use both? can I use allOf only? or join only? or they work together.
My use case is I'm calling n of tasks in async using completableFuture but I want to combile the results of them together.
答案1
得分: 1
join()
不是一个静态方法。它是一个阻塞调用,等待 CompletableFuture
完成计算并返回结果。
allOf()
是一个非阻塞的静态方法,返回一个新的 CompletableFuture
,它“包装”了传递给它的 CompletableFutures
,并在所有传递给它的 CompletableFutures
完成时自身完成。
英文:
join()
is not a static method. It's a blocking call that waits for the CompletableFuture
to finish its calculation and return the result.
allOf()
is a non-blocking static method that returns a new CompletableFuture
that "wraps" the CompletableFutures
passed to it and itself completes when all of the CompletableFutures
passed to it have completed.
答案2
得分: 0
你对于 join
的理解是非常错误的。根据 Java 文档:
public T join()
在完成时返回结果值,或者如果异常完成则抛出(未检查的)异常。
为更好地符合常见的函数形式的使用,如果在完成此 CompletableFuture 的计算中引发异常,该方法将抛出(未检查的)CompletionException,并将底层异常作为其原因。
返回值:
结果值
抛出:
CancellationException - 如果计算被取消
CompletionException - 如果此 future 异常完成
或者完成计算引发异常
因此,它们之间的不同包括:
- 涉及的 future 数量:一个与多个
- 调用是否等待完成
- 返回值 - 结果与另一个可完成的 future
- 异常的处理方式。
也就是说,它们几乎完全不可比较。
英文:
You are very wrong about join
. Per the java doc:
<pre>
public T join()
Returns the result value when complete, or throws an (unchecked)
exception if completed exceptionally. To better conform
with the use of common functional forms, if a computation
involved in the completion of this CompletableFuture threw
an exception, this method throws an (unchecked)
CompletionException with the underlying exception as its cause.
Returns:
the result value
Throws:
CancellationException - if the computation was cancelled
CompletionException - if this future completed exceptionally
or a completion computation threw an exception
</pre>
So - amongst the differences are:
- The number of futures involved: one versus many
- Whether the call waits for completion
- Return value - the result, versus another completeable future.
- The handling of exceptions.
i.e., they are hardly comparable at all.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论