Java并发性:是否需要取消期货才能收集垃圾? [英] Java Concurrency: Is cancelling Futures necessary for them to be Garbage Collected?

查看:40
本文介绍了Java并发性:是否需要取消期货才能收集垃圾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些代码,可能需要创建无数个将来的对象(java.util.concurrent.Future).

I am writing some code where I might need to create an unbounded number of future objects (java.util.concurrent.Future).

但是我担心内存会耗尽.

But I am worried about running out of memory at some point.

问题在这里:

  1. jvm是否知道一旦将来完成,就不会在任何地方引用它,因此有资格使用GC(即使创建它的线程仍在运行并可以运行)?
  2. 理想情况下,我不想跟踪这些期货本身.但是,如果我确实保留了这些期货的参考,并定期对它们进行取消交易,那将使它们可用于GC吗?

推荐答案

您最终需要删除对Future的所有引用,以便对其进行垃圾回收.通常的做法是维护Future的集合,并定期检查isDone()是否返回true.如果是这样,则任务已完成,并且可能会清除对其的引用.如果您担心堆积一些可能会安全中断的长时间运行的任务,则需要同时调用Future上的cancel()并删除/清除可能存在的对它的任何引用.

You'll need to eventually remove any references to the Futures in order for them to be garbage collected. The usual practice is to maintain a collection of the Futures and periodically check whether isDone() returns true. If so, the task has completed and references to it may be cleaned up. If you are worried about piling up some long-running tasks which may be safely interrupted, you need to both call cancel() on the Future and remove/null out any references to it which may exist.

通常,构建一个可能经历无穷增长的系统总是一个坏主意.如果未完成的Future对象的数量过大,则应在系统中的其他位置施加反压力.

In general, it is always a bad idea to architect a system which can potentially experience unbounded growth. If the number of outstanding Future objects grows too large, you should apply back pressure elsewhere in the system.

并不一定是一旦将来完成,就不会在任何地方引用它".例如,引用它的客户端可以随时通过get()方法请求结果.因此,JVM必须保持Future有效,直到所有这些外部引用都被删除为止.当Future被完成"(意味着它已完成其任务或被取消)时,线程池中的引用将被删除.

It is not necessarily the case that "once the future has completed, it is not being referenced anywhere." For example, a client with reference to it could request the result via the get() method at any point. The JVM therefore needs to keep the Future live until all these external references have been removed. The references within the thread pool will be removed when the Future is "done" (meaning either it completed its task or was cancelled).

这篇关于Java并发性:是否需要取消期货才能收集垃圾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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