开发者

Weak reference not getting garbage collected?

I was studying about Weak references. 开发者_C百科And I understood that all weak references WILL be garbage collected before OutOfMemoryError occurs. I had a simple test something like this (I know catching OOME is not good but just a test) :

Integer weakInt = new Integer(10);
WeakReference<Integer> weakReference = new WeakReference<Integer>(weakInt);

try {
    while (weakReference != null) {
        String[] generateOutOfMemoryStr = new String[999999999];
    }
}
catch (OutOfMemoryError oome) {
   System.out.println(weakReference.get());
}

I expected null to be printed because the weak reference SHOULD have been collected but I always get an output of 10.

Please let me know where I am going wrong. May be I understood the concept of weak references wrong?


weakReference itself won't become null... how could it? However, its target can become null.

I suspect you mean:

while (weakReference.get() != null) {

Moreover, I suspect that unless you set weakInt itself to null, that local variable will prevent the Integer object from being garbage collected.

Moreover, I suspect you'll find your loop still won't end - because you're quite possibly asking for more memory than can be allocated even if the Integer is garbage collected.

Here's a program which demonstrates it working, at least on my box:

import java.lang.ref.*;

public class Test {
    public static void main(String[] args) {
        Integer weakInt = new Integer(10);
        WeakReference<Integer> weakReference = new WeakReference<Integer>(weakInt);

        weakInt = null;
        while (weakReference.get() != null) {
            System.out.println("Looping...");
            String[] generateOutOfMemoryStr = new String[999999];
        }
        System.out.println("Weak reference collected");
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜