Java Concurrency: Is cancelling Futures necessary for them to be Garbage Collected?

有些话、适合烂在心里 提交于 2019-12-06 02:10:43

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.

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.

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).

Diana Sule

Have you seen this question?

Once the computation of a Future is complete, you cannot cancel it anymore. I don't know the exact context, but one suggestion would be to keep track of the futures, cancel the ones you want or need to cancel and call purge on the executor to remove them from the working queue.

Hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!