未来的垃圾收集 [英] CompletableFuture and Garbage Collection
问题描述
我想触发许多一次性的异步CompletableFuture,例如:
I'd like to fire many one-off async CompletableFutures, like so:
for (Job job : jobs) {
CompletableFuture.supplyAsync(() -> job.process())
.whenComplete(this::doSomething);
}
理想地,这些CompletableFuture可以在whenComplete
完成之后被垃圾回收.但是,由于我没有存储参考文献,因此它们有被事先收集的风险吗?
Ideally these CompletableFutures could be garbage collected after whenComplete
has finished. But is there a risk they are collected beforehand, since I'm not storing a reference?
推荐答案
您没有显式存储引用,但是supplyAsync
在内部.该方法创建一个CompletableFuture
,并将一个引用返回给ForkJoinPool
的任务提交给ForkJoinPool
(如果您使用的是公共池). whenComplete
返回的CompletableFuture
依赖于第一个CompletableFuture
,因此也被引用.
You're not explicitly storing a reference, but supplyAsync
is, internally. The method creates a CompletableFuture
and submits a task to the ForkJoinPool
(if you're using the common pool) that has a reference back to it. The CompletableFuture
returned by whenComplete
becomes a dependent on that first CompletableFuture
and so is also referenced.
一旦ForkJoinPool
完成执行Supplier
,将第一个CompletableFuture
标记为完成,触发第二个CompletableFuture
并执行传递给whenComplete
.
All these objects will be available for garbage collection once the ForkJoinPool
completes execution of the Supplier
, marks the first CompletableFuture
as complete, triggers the second CompletableFuture
, and executes the BiConsumer
passed to whenComplete
.
您很安全.
这篇关于未来的垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!