假设我有一个如下所示的引用树:
root => WeakHashMap<View, Binder> => Binder => View
// by WeakHashMap I mean keys (Views) are referenced by WeakReferences
// View is only referenced by Binder
View
(和Binder
)会被收集吗?或者从 Binder
到 View
的引用也必须是弱的吗?
这就是代码中的样子:
class SomeClass {
private static final Map<View, Binder> binders = new WeakIdentityHashMap<>();
// (...)
}
class Binder {
private final View target;
public Binder(View target) {
this.target = target
}
// (...)
}
最佳答案
没有。
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.
至于从值到键的WeakReference:
是的。
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.
关于java - 在这种情况下对象会被收集吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23308882/