1. 程式人生 > >java類的生命週期-強引用,弱引用,虛引用,軟引用

java類的生命週期-強引用,弱引用,虛引用,軟引用

1.強引用

package com.cap3;

public class Test1 {
    static Object strongRefence=new Object();
    public static void main(String[] args) {
       Object object=strongRefence;
       strongRefence=null;
       System.gc();
       System.out.println("After gc->"+object);
    }
}

//列印結果

After gc->
[email protected]

強引用會被回收的情況:

脫離作用域

2.軟引用

package com.cap3;

import java.lang.ref.SoftReference;

public class Test1 {
    public static void main(String[] args) {
        Object object=new Object();
        //發生OOM異常前會被回收
        SoftReference<Object> softReference=new SoftReference<Object>(object);
        System.out.println(softReference.get());
        
    }
}

軟引用會被回收的情況:

軟引用在記憶體充足的情況下不會被回收,在記憶體不足的情況下,軟引用才會被回收,避免發生OOM

3.弱引用

package com.cap3;

import java.lang.ref.WeakReference;

public class Test1 {
    public static void main(String[] args) {
        Object object=new Object();
        WeakReference<Object> weakReference=new WeakReference<Object>(object);
        object=null;
        System.gc();
        System.out.println("After Gc->"+weakReference.get());
    }
}

軟引用會被回收的情況:

是個Gc就把他滅了

4.虛引用

package com.cap3;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;

public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        //引用佇列
        ReferenceQueue referenceQueue=new ReferenceQueue();
        Object phantomObj=new Object();
        PhantomReference phantomReference=new PhantomReference(phantomObj,referenceQueue);
        phantomObj=null;
        System.gc();
        //System.out.println(phantomReference.get());
        //虛引用要通過引用佇列去取值
        Thread.sleep(500);
        System.out.println(referenceQueue.poll());
    }
}

虛引用主要用來追蹤物件