WeakReference对象是否也与引用的对象一起收集垃圾?

时间:2015-03-30 18:12:16

标签: java android weak-references

考虑下一个片段:

private void foo() {
    A a = new A();
    WeakReference<A> weakA = new WeakReference<A>(a);
    a = null;

    while (true) {
        if (weakA.get() != null)
            System.out.println("weakA.get() != null !!!"); 
        else
            System.out.println("weakA.get() == null"); 
    }
}

&#39; if&#39;句子还包含对“弱”的空值检查。 object(WeakReference对象)?像这样:

if (weakA != null && weakA.get() != null)

或者只是这种情况下的冗余检查?我问这个是因为我看过很多代码和教程,检查WeakReference是否为空,我不确定是否因为当保存的引用对象是GC时,VM会擦除WeakReference本身。

提前致谢。

编辑:

您可以在本教程中查看此模式的示例以进行空检查: http://android-developers.blogspot.com.ar/2010/07/multithreading-for-performance.html

但我也在Multithreading For Performance找到了它。在这种情况下,它检查AsyncTask.onPostExecute()方法中的WeakReference是否为空,但是它没有明确地为WeakReference对象赋值,所以我猜测检查WeakReference本身是否为空是多余的。

2 个答案:

答案 0 :(得分:1)

不,weakA本身不能是null,只要您仍然拥有对它的引用。这只是可以收集的对象。

您可以发布您提到的代码示例吗?

答案 1 :(得分:0)

由于您已在方法foo()中创建了WeakReference对象:

WeakReference<A> weakA = new WeakReference<A>(a);

这意味着weakA没有机会为null,除非在任何阶段的方法foo()中你自己为null。 如果在下一个垃圾收集周期中它们为null,则将收集weakA中的所有对象。在上面的示例对象&#34; a&#34;将成为下一个周期垃圾收集的候选人。