我是否需要保持对仅用于执行最终化的WeakReference的强烈参考? [英] Do I need to keep a strong reference to a WeakReference that is only used to perform finalization?

查看:187
本文介绍了我是否需要保持对仅用于执行最终化的WeakReference的强烈参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用WeakReference作为更有效率的finalize()方法,目的是尽可能快地释放与对象相关联的本机资源,而无需使用定稿(成本显着较高比使用WeakReference)。

因为这是WeakReference的唯一目的(我永远不会使用WeakReference来获取引用的对象),所以采取时间和空间来维护我的WeakReferences的列表,以防止它们被垃圾收集。



但是,如果构造一个普通的对象并且没有强大的引用保留,将被垃圾收集器简单地释放,并且我无法在Javadoc中找到任何暗示这与WeakReference不同的任何内容。



是否有必要保留一个引用为了防止它被垃圾收集,或者如果它被排入参考队列中,它会保持活跃直到它成为蜜蜂n从队列中收集?

解决方案


是否有必要保留对WeakReference的引用以防止它被垃圾收集


查看 java.lang.ref 包装说明,它专门用一整段来回答你的问题:


注册引用对象与其队列之间的关系是单向的。也就是说,一个队列不跟踪注册的引用。如果注册的引用本身变得无法访问,那么它永远不会入队。程序使用引用对象负责确保只要程序对其对象感兴趣,对象就可以保持可达状态。



I'd like to use a WeakReference as a more efficient finalize() method, for the purpose of freeing native resources associated with an object as soon as it becomes possible to do so, without using finalization (which has significantly higher costs than using a WeakReference).

Since this is the only purpose of the WeakReference (I will never use the WeakReference to obtain the referenced object), it seems wasteful to take the time and space to maintain a list of my WeakReferences to prevent them from being garbage collected.

But if a normal object is constructed and no strong reference is kept to it, it will simply be freed by the garbage collector, and I can't find anything in the Javadoc that suggests this is different for a WeakReference.

Is it necessary to keep a reference to a WeakReference to prevent it from being garbage collected, or, if it's to be enqueued in a ReferenceQueue, will that keep it alive until it's been collected from the queue?

解决方案

Is it necessary to keep a reference to a WeakReference to prevent it from being garbage collected

Have a look at the java.lang.ref package description, it dedicates a whole paragraph to answering your question:

The relationship between a registered reference object and its queue is one-sided. That is, a queue does not keep track of the references that are registered with it. If a registered reference becomes unreachable itself, then it will never be enqueued. It is the responsibility of the program using reference objects to ensure that the objects remain reachable for as long as the program is interested in their referents.

这篇关于我是否需要保持对仅用于执行最终化的WeakReference的强烈参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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