سؤال

Let's say I have a reference tree that looks like that:

root => WeakHashMap<View, Binder> => Binder => View
// by WeakHashMap I mean keys (Views) are referenced by WeakReferences
// View is only referenced by Binder

Will View (and Binder) get collected? Or does reference from Binder to View also has to be weak?

That's how it looks in code:

class SomeClass {
    private static final Map<View, Binder> binders = new WeakIdentityHashMap<>();
    // (...)
}

class Binder {
    private final View target;

    public Binder(View target) {
        this.target = target
    }
    // (...)
}
هل كانت مفيدة؟

المحلول

No.

http://docs.oracle.com/javase/7/docs/api/java/util/WeakHashMap.html

Implementation note: The value objects in a WeakHashMap are held by ordinary strong references. Thus care should be taken to ensure that value objects do not strongly refer to their own keys, either directly or indirectly, since that will prevent the keys from being discarded. Note that a value object may refer indirectly to its key via the WeakHashMap itself; that is, a value object may strongly refer to some other key object whose associated value object, in turn, strongly refers to the key of the first value object. If the values in the map do not rely on the map holding strong references to them, one way to deal with this is to wrap values themselves within WeakReferences before inserting, as in: m.put(key, new WeakReference(value)), and then unwrapping upon each get.

As for WeakReference from value to key:

Yes.

http://docs.oracle.com/javase/7/docs/api/java/lang/ref/package-summary.html#reachability

An object is weakly reachable if it is neither strongly nor softly reachable but can be reached by traversing a weak reference. When the weak references to a weakly-reachable object are cleared, the object becomes eligible for finalization.

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