morfys
morfys

Reputation: 2415

Are WeakReferences in a ReferenceQueue automatically removed from the queue?

I know that for PhantomReference's in the ReferencesQueue, one has to handle and empty the ReferenceQueue oneself.

In the case of WeakReferences in the ReferenceQueue, are the WeakReferences automatically removed from the ReferenceQueue?

We've used a strategy as an alternative to finalizers as described here: http://resources.ej-technologies.com/jprofiler/help/doc/indexRedirect.html?http&&&resources.ej-technologies.com/jprofiler/help/doc/helptopics/config/finalizers.html

but we don't want to have another thread for removing PhantomReference's from the ReferenceQueue.

So we used WeakReferences instead, assuming that they are automatically removed from the ReferenceQueue. Is this a correct assumption? Thank you.

Upvotes: 2

Views: 424

Answers (2)

WPrecht
WPrecht

Reputation: 1382

Yes, you are correct. Unless some whacky finalization code resurrects them.

Here's a good article explaining the situation: https://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html

Upvotes: 1

Chaffers
Chaffers

Reputation: 176

Weak references will be GC'ed along with the object they reference, providing there is no other references to that object. Hence weak references in a ReferenceQueue will not do what you are expecting them to do. The weak reference will not prevent the object from being GC'ed, but once it is you will not be able to get an indirect reference to it in the same way as a phantom reference.

Saying that try using weak references on Websphere and you'll find that the garbage collector is ultra aggressive in clearing them out, whether you like it or not.

You will need to clean the phantom references up yourself with a daemon thread, possibly including some form of destructor.

Upvotes: 1

Related Questions