java - 在这种情况下对象会被收集吗?

标签 java weak-references

假设我有一个如下所示的引用树:

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

View(和Binder)会被收集吗?或者从 BinderView 的引用也必须是弱的吗?

这就是代码中的样子:

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/

相关文章:

rust - 存储对自身的引用

java - 弱引用 : reference is destroyed within "seconds"

java - native Thread 类函数的 JNI 流程是什么?

java - 我需要使用多个 AsyncTask 子类吗?

Java 清理 Arraylist 记录的建议

Scala 在案例类中使用 Wea​​kReference

python - 在不使用临时文件的情况下通过 __get__ 调用 __iadd__ 时发生内存泄漏

c++ - weak_ptr 是如何工作的?

java - JSF Web 项目 <h :xxx> tag invisible

java - 如何旋转缓冲图像,然后将缓冲图像复制到像素数组中