Java引用對象SoftReference WeakReference PhantomReference(二)

來源:互聯網
上載者:User

四、Java對引用的分類

層級

什麼時候被記憶體回收

用途

存留時間

從來不會

對象的一般狀態

JVM停止運行時終止

在記憶體不足時

對象簡單?緩衝

記憶體不足時終止

在記憶體回收時

對象緩衝

gc運行後終止

假象

Unknown

Unknown

Unknown

1、強引用:

public static void main(String[] args) {

        MyDate date = new MyDate();

        System.gc();

}

解釋:即使顯式調用了記憶體回收,但是用於date是強引用,date沒有被回收

2、軟引用:

public static void main(String[] args) {

        SoftReference ref = new SoftReference(new MyDate());

        drainMemory(); // 讓軟引用工作

}

解釋:在記憶體不足時,軟引用被終止,等同於:

MyDate date = new MyDate();

//-------------------由JVM決定運行-----------------

If(JVM.記憶體不足()) {

         date = null;

         System.gc();

}

//-------------------------------------------------------------

3、弱引用:

public static void main(String[] args) {

        WeakReference ref = new WeakReference(new MyDate());

        System.gc(); // 讓弱引用工作

}

解釋:在JVM記憶體回收運行時,弱引用被終止,等同於:

MyDate date = new MyDate();

//------------------記憶體回收運行------------------

public void WeakSystem.gc() {

         date = null;

         System.gc();

}

4、假象引用:

public static void main(String[] args) {

        ReferenceQueue queue = new ReferenceQueue();

        PhantomReference ref = new PhantomReference(new MyDate(), queue);

        System.gc(); // 讓假象引用工作

}

解釋:假象引用,在執行個體化後,就被終止了,等同於:

MyDate date = new MyDate();

date = null;

//-------終止點,在執行個體化後,不是在gc時,也不是在記憶體不足時--------

 

 

http://hi.baidu.com/mynetbeans/blog/item/d72208fa8d63ac1ba9d31160.html

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.