标题翻译
How to run a cleaning action with a reference to the object being registered
问题
自从Java 9以来,我们终于拥有了Cleaner
。然而在文档中明确声明:
> 每个Cleaner都是独立操作的,管理挂起的清理操作,并在不再使用Cleaner时处理线程和终止。
>
> 注册对象引用和相应的清理操作将返回一个Cleanable。最高效的用法是在对象关闭或不再需要时显式调用clean方法。
>
> 清理操作是一个Runnable,在对象变为虚引用可达时最多被调用一次,除非已经显式进行了清理。
>
> *请注意,清理操作不能引用正在注册的对象。*如果这样做,对象将不会变为虚引用可达,清理操作不会被自动调用。
不幸的是,这正是我所需要的:我想要注册的操作需要引用对象本身(通常只是调用一个方法)。
由于使用Cleaner似乎不可能实现这一点,是否有办法使用虚引用或弱引用来实现?
我查看了它们,它们看起来相当复杂,所以在认真深入研究它们之前,我想事先知道是否可能做到这样的操作。
附注:显然,虚引用现在看起来是在对象死后执行的。
英文翻译
Since java 9 we finally have Cleaner
. However in the docs is specifically declared:
> Each cleaner operates independently, managing the pending cleaning actions and handling threading and termination when the cleaner is no longer in use.
>
> Registering an object reference and corresponding cleaning action returns a Cleanable. The most efficient use is to explicitly invoke the clean method when the object is closed or no longer needed.
>
> The cleaning action is a Runnable to be invoked at most once when the object has become phantom reachable unless it has already been explicitly cleaned.
>
> Note that the cleaning action must not refer to the object being registered. If so, the object will not become phantom reachable and the cleaning action will not be invoked automatically.
Unfortunately, this is exactly what I would need: the action I want to register needs to refer the object itself (usually it's nothing else then calling a method).
Since this looks not possible with the Cleaner, is there a way to do it using Phantom or weak/soft references?
I took a look at them, and they look fairly complicate, so before investing quite some time digging into them seriously, I'd like to know in advance if something like this is possible or not
Ps: apparently it looks like Phantom references now get executed post-mortem
专注分享java语言的经验与见解,让所有开发者获益!
评论