Is there a way to be alerted when a WeakReference is removed? I need to add an Android Context to an Instance, I am adding this as a WeakReference and then I would like to handle a few things when/if this is removed? I think that I read about this somewhere, but of cause I can't remember where and searching for it gives me nothing :(
Weak Reference (wr) doesn't provide a call back. If you need a proper call back, the finalize method of the object can be overriden to do something when it's been garbage collected (gc'd).
What wr does provide is a referenceQueue (rq), which is basicaly a list of references whose referents haven't been gc'd. You attach a referenceQueue in the constructor of the reference.
ReferenceQueue<Drawable> rq = new ReferenceQueue<Drawable>();
WeakReference<Drawable> wr = new WeakReference<Drawable>(dr, rq);
Once our drawable is gc'd, referenceQueue should contain the wr.
do{
Reference<?> ref = rq.poll(); //this should be your weak reference
if(ref == null) break;
ref.get(); //Should always be null, cause referent is gc'd
// do something
}while(true);
We probably put wr in a map because we don't have any way of telling what "wr" is when we get it back from rq -- after all its referrent is null. It's only significance is what it referred to, and that doesn't exist any more, so we need a record of this significance, so we put it in map, keyed to some action we'd like to take, which may even be just deleting the weak reference itself from the map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With