Java中弱引用的理解

弱引用也是用来描述非必需的对象,但是他的强度比软引用更弱一些,被弱引用关联的对象只能生存到下一次垃圾收集发生之前,当垃圾收集工作时,无论当前内存是否足够,都会回收掉被弱引用关联的对象,在JDK1.2之后,提供了WeakReference类实现弱引用。

看下面的代码

public class TestClient {
        public static void main(String[] args) throws Exception {
                int count = 5;
    System.out.println("before create object the current memory size = " +                 Runtime.getRuntime().freeMemory());
    Test test = new Test();
    System.out.println("after create object the current memory size = " + Runtime.getRuntime().freeMemory());
    WeakReference<Test> weakReference = new WeakReference<Test>(test);
    while(true) {
        count--;
        System.gc();
        Thread.sleep(5000);
        if(weakReference.get() == null) {
            System.out.println("the test has been recycled and the free memory is " + Runtime.getRuntime().freeMemory());
        } else {
            System.out.println("the test has not been recycled and the free memory is " + Runtime.getRuntime().freeMemory());
            if(count == 0) {
                test = null;
            }
        }
    }
    }
}
class Test  {
    byte data [] = new byte[10 * 1024 * 1024];
}

上述代码运行的结果如下

before create object the current memory size = 122179856
after create object the current memory size = 111694080
the test has not been recycled and the free memory is 112663384
the test has not been recycled and the free memory is 112666448
the test has not been recycled and the free memory is 113316792
the test has not been recycled and the free memory is 113316792
the test has not been recycled and the free memory is 113316792
the test has been recycled and the free memory is 123802584
the test has been recycled and the free memory is 123802440
the test has been recycled and the free memory is 123802440

我们可以发现我们通过WeakReference 引用到了 Test 对象,但是一旦我们把test这个强引用置为null之后,test对象马上就被回收了。

如果把弱引用改为软引用,那么会发现即使把test置为空,这个对象依然被软引用引用到了,不会不会被垃圾回收器回收。在Java虚拟机中,被软引用引用到的对象只会在内存不够用的情况下才会回收这一部分内存。