Do I need to keep a strong reference to a WeakRefe

2019-05-31 10:05发布

问题:

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.