سؤال

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.

نصائح أخرى

The preferred way to do this is to use a ReferenceQueue<T> as @NameSpace indicated. However, a common pattern is to extend the WeakReference<T> so you can keep identifying information in it. (Clearly, this should not be the garbage collected object or something that has a reference to it.)

For example, the WeakHashMap<K,V> expunges garbage collected keys of type K. It has an Entry class for each entry that extends WeakReference<Object>. The constructor of Entry adds it to the WeakHashMap's reference queue. The key K of the entry, is stored as the actual weak reference in the super class. The value V is stored in the subclass. Any entry on this queue is then removed.

Take a look at java.util.WeakHashMap for further details.

At every put, the Reference Queue is checked. The poll() method returns a Reference but this can be casted to an Entry.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top