gpt4 book ai didi

java - Completable Future什么时候将线程释放回线程池?

转载 作者:行者123 更新时间:2023-12-03 18:33:05 25 4
gpt4 key购买 nike

什么时候 CompletableFuture 将线程释放回 ThreadPool ?是调用get()方法后还是关联任务完成后?

最佳答案

get 调用与池中的线程之间没有任何关系。 future 的完成与线程之间甚至没有关系。

CompletableFuture 可以从任何地方完成,例如通过在其上调用 complete。当您使用其中一种便捷方法将任务安排给最终将尝试完成它的执行器时,线程将一直用到那个点,当进行完成尝试时,无论 future 是否已经完成。

例如,

CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> "hello");

在语义上等同于

CompletableFuture<String> f = new CompletableFuture<>();

ForkJoinPool.commonPool().execute(() -> {
try {
f.complete("hello");
} catch(Throwable t) {
f.completeExceptionally(t);
}
});

很明显,线程池和计划的操作都不关心将来是否有人调用 get()join()

即使您提前完成 future ,例如通过 complete("some other string") 或通过 cancel(…),它对正在进行的计算没有影响,因为没有从 future 到作业的引用.作为the documentation of cancel states :

Parameters:

mayInterruptIfRunning - this value has no effect in this implementation because interrupts are not used to control processing.

看了上面的解释,应该很清楚为什么了。

创建依赖链时会有所不同,例如通过 b = a.thenApply(function)。将评估 function 的作业将不会在 a 完成之前提交。当 a 完成时,b 的完成状态将在 function 开始评估之前重新检查。如果此时 b 已完成,则可能会跳过评估。

CompletableFuture<String> a = CompletableFuture.supplyAsync(() -> {
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
return "foo";
});
CompletableFuture<String> b = a.thenApplyAsync(string -> {
System.out.println("starting to evaluate "+string);
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
System.out.println("finishing to evaluate "+string);
return string.toUpperCase();
});
b.complete("faster");
System.out.println(b.join());
ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.DAYS);

只会打印

faster

但是评价一旦开始就无法停止,所以

CompletableFuture<String> a = CompletableFuture.supplyAsync(() -> {
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
return "foo";
});
CompletableFuture<String> b = a.thenApplyAsync(string -> {
System.out.println("starting to evaluate "+string);
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
System.out.println("finishing to evaluate "+string);
return string.toUpperCase();
});
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
b.complete("faster");
System.out.println(b.join());
ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.DAYS);

将打印

starting to evaluate foo
faster
finishing to evaluate foo

表明,即使在您成功从较早完成的 future 中检索到值时,可能仍有仍在运行的后台计算将尝试完成 future 。但随后的完成尝试将被忽略。

关于java - Completable Future什么时候将线程释放回线程池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48213670/

25 4 0