Do I need to keep a strong reference to a WeakReference that is only used to perform finalization?

柔情痞子 提交于 2020-01-14 04:31:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/32108427/do-i-need-to-keep-a-strong-reference-to-a-weakreference-that-is-only-used-to-per

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