Detecting when a WeakReference gets cleared.

D

Dave Rudolf

Hi all,

This might be a better question for the VM newsgroup, but they don't seem to
get a lot of readers there, so I thought I would try this group:

Suppose that I have a collection of WeakReference objects, and I want to
know when the referent object is finalized by the garbage collector so that
I can remove the reference from the collection. I noticed that the Reference
class has a public non-final method called clear(), and also when I look at
the java source code for Reference (jdk1.4.1_01-b01) , this clear() method
is the only place where the referent is getting set to null. I figured that
I could override this clear() method to notify listeners of what is
happening. So I decided to write my own reference class like so

public class BetterThanWeakReference extends
java.lang.ref.WeakReference
{

public BetterThanWeakReference( final Object referent )
{
super( referent );
}

public void clear()
{
super.clear();
/** @todo Fire events, or whatever */
System.err.println( "Cleared" );
}
}

If I then create hordes and hordes of these references, and then try to get
the referent, I pretty much always get null, yet my overridden method is
never called. Is there some JVM voodoo happening here that is setting the
reference's referent to null without calling clear()???


Dave
 
L

Laird Nelson

Dave said:
Suppose that I have a collection of WeakReference objects, and I want to
know when the referent object is finalized by the garbage collector so that
I can remove the reference from the collection.

You might have a look at ReferenceQueues. I haven't used them myself,
but they seem to be designed to alert you to when an object's
reachability status has changed.

Cheers,
Laird
 
A

Adam Maass

Laird Nelson said:
You might have a look at ReferenceQueues. I haven't used them myself,
but they seem to be designed to alert you to when an object's
reachability status has changed.

That's precisely what they're for.

Note that the notification is not "when an object's reachability status has
changed" but "sometime after an object's reachability status has changed."
And the only change that is noticed is from any of the reachable statuses to
unreachable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top