未来的垃圾收集 [英] CompletableFuture and Garbage Collection

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

问题描述

我想触发许多一次性的异步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屋!

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