日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

Java常見的四種引用

 huhuwoo 2015-10-17

從JDK1.2版本開始,把對象的引用分為四種級別,從而使程序能更加靈活的控制對象的生命周期。這四種級別由高到低依次為:強引用、軟引用、弱引用和虛引用。

1.強引用

本章前文介紹的引用實際上都是強引用,這是使用最普遍的引用。如果一個對象具有強引用,那就 類似于必不可少的生活用品,垃圾回收器絕不會回收它。當內(nèi)存空 間不足,Java虛擬機寧愿拋出OutOfMemoryError錯誤,使程序異常終止,也不會靠隨意回收具有強引用的對象來解決內(nèi)存不足問題。

2.軟引用(SoftReference)

如果一個對象只具有軟引用,那就類似于可有可物的生活用品。如果內(nèi)存空間足夠,垃圾回收器就不會回收它,如果內(nèi)存空間不足了,就會回收這些對象的內(nèi)存。只要垃圾回收器沒有回收它,該對象就可以被程序使用。軟引用可用來實現(xiàn)內(nèi)存敏感的高速緩存。
軟引用可以和一個引用隊列(ReferenceQueue)聯(lián)合使用,如果軟引用所引用的對象被垃圾回收,Java虛擬機就會把這個軟引用加入到與之關(guān)聯(lián)的引用隊列中。

3.弱引用(WeakReference)

如果一個對象只具有弱引用,那就類似于可有可物的生活用品。 弱引用與軟引用的區(qū)別在于:只具有弱引用的對象擁有更短暫的生命周期。在垃圾回收器線程掃描它 所管轄的內(nèi)存區(qū)域的過程中,一旦發(fā)現(xiàn)了只具有弱引用的對象,不管當前內(nèi)存空間足夠與否,都會回收它的內(nèi)存。不過,由于垃圾回收器是一個優(yōu)先級很低的線程, 因此不一定會很快發(fā)現(xiàn)那些只具有弱引用的對象。
弱引用可以和一個引用隊列(ReferenceQueue)聯(lián)合使用,如果弱引用所引用的對象被垃圾回收,Java虛擬機就會把這個弱引用加入到與之關(guān)聯(lián)的引用隊列中。

4.虛引用(PhantomReference)

"虛引用"顧名思義,就是形同虛設,與其他幾種引用都不同,虛引用并不會決定對象的生命周期。如果一個對象僅持有虛引用,那么它就和沒有任何引用一樣,在任何時候都可能被垃圾回收。
虛 引用主要用來跟蹤對象被垃圾回收的活動。虛引用與軟引用和弱引用的一個區(qū)別在于:虛引用必須和引用隊列(ReferenceQueue)聯(lián)合使用。當垃 圾回收器準備回收一個對象時,如果發(fā)現(xiàn)它還有虛引用,就會在回收對象的內(nèi)存之前,把這個虛引用加入到與之關(guān)聯(lián)的引用隊列中。程序可以通過判斷引用隊列中是 否已經(jīng)加入了虛引用,來了解被引用的對象是否將要被垃圾回收。程序如果發(fā)現(xiàn)某個虛引用已經(jīng)被加入到引用隊列,那么就可以在所引用的對象的內(nèi)存被回收之前采取必要的行動。

在本書中,"引用"既可以作為動詞,也可以作為名詞,讀者應該根據(jù)上下文來區(qū)分"引用"的含義。

在java.lang.ref包中提供了三個類:SoftReference類、WeakReference類和PhantomReference 類,它 們分別代表軟引用、弱引用和虛引用。ReferenceQueue類表示引用隊列,它可以和這三種引用類聯(lián)合使用,以便跟蹤Java虛擬機回收所引用的對 象的活動。以下程序創(chuàng)建了一個String對象、ReferenceQueue對象和WeakReference對象:

  1. //創(chuàng)建一個強引用 
  2. String str = new String("hello"); 
  3. //創(chuàng)建引用隊列, <String>為范型標記,表明隊列中存放String對象的引用 
  4. ReferenceQueue<String> rq = new ReferenceQueue<String>(); 
  5. //創(chuàng)建一個弱引用,它引用"hello"對象,并且與rq引用隊列關(guān)聯(lián) 
  6. //<String>為范型標記,表明WeakReference會弱引用String對象 
  7. WeakReference<String> wf = new WeakReference<String>(str, rq); 

以上程序代碼執(zhí)行完畢,內(nèi)存中引用與對象的關(guān)系如圖11-10所示。

圖11-10 "hello"對象同時具有強引用和弱引用

在圖11-10中,帶實線的箭頭表示強引用,帶虛線的箭頭表示弱引用。從圖中可以看出,此時"hello"對象被str強引用,并且被一個WeakReference對象弱引用,因此"hello"對象不會被垃圾回收。

在以下程序代碼中,把引用"hello"對象的str變量置為null,然后再通過WeakReference弱引用的get()方法獲得"hello"對象的引用:

  1. String str = new String("hello"); //① 
  2. ReferenceQueue<String> rq = new ReferenceQueue<String>(); //② 
  3. WeakReference<String> wf = new WeakReference<String>(str, rq); //③ 
  4. str=null; //④取消"hello"對象的強引用 
  5. String str1=wf.get(); //⑤假如"hello"對象沒有被回收,str1引用"hello"對象 
  6. //假如"hello"對象沒有被回收,rq.poll()返回null 
  7. Reference<? extends String> ref=rq.poll(); //⑥ 

執(zhí)行完以上第④行后,內(nèi)存中引用與對象的關(guān)系如圖11-11所示,此 時"hello"對象僅僅具有弱引用,因此它有可能被垃圾回收。假如它還沒有被垃圾回收,那么接下來在第⑤行執(zhí)行wf.get()方法會返 回"hello"對象的引用,并且使得這個對象被str1強引用。再接下來在第⑥行執(zhí)行rq.poll()方法會返回null,因為此時引用隊列中沒有任 何引用。ReferenceQueue的poll()方法用于返回隊列中的引用,如果沒有則返回null。

圖11-11 "hello"對象只具有弱引用

在以下程序代碼中,執(zhí)行完第④行后,"hello"對象僅僅具有弱引用。接下來兩次調(diào)用System.gc()方法,催促垃圾回收器工作,從而提 高"hello"對象被回收的可能性。假如"hello"對象被回收,那么WeakReference對象的引用被加入到ReferenceQueue 中,接下來wf.get()方法返回null,并且rq.poll()方法返回WeakReference對象的引用。圖11-12顯示了執(zhí)行完第⑧行后 內(nèi)存中引用與對象的關(guān)系。

  1. String str = new String("hello"); //① 
  2. ReferenceQueue<String> rq = new ReferenceQueue<String>(); //② 
  3. WeakReference<String> wf = new WeakReference<String>(str, rq); //③ 
  4. str=null; //④ 
  5. //兩次催促垃圾回收器工作,提高"hello"對象被回收的可能性 
  6. System.gc(); //⑤ 
  7. System.gc(); //⑥ 
  8. String str1=wf.get(); //⑦ 假如"hello"對象被回收,str1為null 
  9. Reference<? extends String> ref=rq.poll(); //⑧ 

圖11-12 "hello"對象被垃圾回收,弱引用被加入到引用隊列

The important part about strong references -- the part that makes them "strong" -- is how they interact with the garbage collector. Specifically, if an object is reachable via a chain of strong references (strongly reachable), it is not eligible for garbage collection. As you don't want the garbage collector destroying objects you're working on, this is normally exactly what you want.

  1. package com.TestRef; 
  2.  
  3. import java.lang.ref.PhantomReference; 
  4. import java.lang.ref.ReferenceQueue; 
  5. import java.lang.ref.SoftReference; 
  6. import java.lang.ref.WeakReference; 
  7. import java.util.Map; 
  8. import java.util.WeakHashMap; 
  9.  
  10. public class Ref { 
  11.     public Ref() { 
  12.     } 
  13.     /** 
  14.      * @param args 
  15.      */ 
  16.     public static void main(String[] args) { 
  17.         try { 
  18. //            test1(); 
  19. //            test2(); 
  20. //            test3(); 
  21. //            test4(); 
  22. //            test5(); 
  23.             test6(); 
  24.         } catch (InterruptedException e) { 
  25.             // TODO Auto-generated catch block 
  26.             e.printStackTrace(); 
  27.         } 
  28.     } 
  29.     /** 強引用,JVM的默認實現(xiàn) */   
  30.     public static void test1() throws InterruptedException {   
  31.         Object obj = new Object();   
  32.         Object strong = obj;   
  33.         obj = null;   
  34.         System.gc();   
  35.         Thread.sleep(1000);   
  36.         System.out.println("strong="+strong); 
  37.     }   
  38.     /**  
  39.      * WeakReference 弱引用( 當所引用的對象在 JVM 內(nèi)不再有強引用時, GC 后weak reference 將會被自動回收)  
  40.      * */   
  41.     public static void test2() throws InterruptedException {   
  42.         Object obj = new Object();   
  43.         WeakReference<Object> wr = new WeakReference<Object>(obj);   
  44.         obj = null;   
  45.         System.gc();   
  46.         Thread.sleep(1000);   
  47.         System.out.println("wr.get()="+wr.get());   
  48.         System.out.println("wr="+wr);   
  49.         wr.clear(); 
  50.         System.out.println("w1111r="+wr.get());   
  51.     }   
  52.     /**  
  53.      * SoftReference SoftReference 于 WeakReference 的特性基本一致, 最大的區(qū)別在于  
  54.      * SoftReference 會盡可能長的保留引用直到 JVM 內(nèi)存不足時才會被回收(虛擬機保證)  
  55.      * */   
  56.     public static void test3() throws InterruptedException {   
  57.         Object obj = new Object();   
  58.         SoftReference<Object> sr = new SoftReference<Object>(obj);   
  59.         obj = null;   
  60.         System.gc();   
  61.         Thread.sleep(1000);   
  62.         System.out.println("sr.get()="+sr.get());   
  63.     }   
  64.     /**  
  65.      * PhantomReference Phantom Reference(幽靈引用) 與 WeakReference 和 SoftReference  
  66.      * 有很大的不同, 因為它的 get() 方法永遠返回 null  
  67.      * */   
  68.     public static void test4() throws InterruptedException {   
  69.         Object obj = new Object();   
  70.         ReferenceQueue<Object> rq = new ReferenceQueue<Object>();   
  71.         PhantomReference<Object> pr = new PhantomReference<Object>(obj, rq);   
  72.         System.out.println("pr.get()="+pr.get());  
  73.     }   
  74.     /** 
  75.      * ReferenceQueue: 
  76.      * @throws InterruptedException 
  77.      */ 
  78.     public static void test5() throws InterruptedException {   
  79.         Object obj = new Object();   
  80.         ReferenceQueue<Object> rq = new ReferenceQueue<Object>();   
  81.         WeakReference<Object> pr = new WeakReference<Object>(obj, rq);   
  82.         System.out.println("**pr.enqueue()="+pr.enqueue());   
  83.         System.out.println("**pr.isEnqueued()="+pr.isEnqueued());       
  84.         System.out.println("**pr="+pr); 
  85.         System.out.println("**rq.poll()="+rq.poll());   
  86.         obj = null;   
  87.         System.gc();   
  88. //        System.out.println("pr.enqueue()="+pr.enqueue());   
  89. //        System.out.println("**pr.isEnqueued()="+pr.isEnqueued());       
  90. //        System.out.println("pr="+pr); 
  91. //        System.out.println("rq.poll()="+rq.poll());   
  92. //        System.out.println("obj5="+obj);   
  93.     }   
  94.      
  95.     /**  
  96.      * 使用 WeakReference 作為 key, 一旦沒有指向 key 的強引用,   
  97.      * WeakHashMap 在 GC 后將自動刪除相關(guān)的  
  98.      * entry  
  99.      */   
  100.     public static void test6() throws InterruptedException {   
  101.         Map<Object, Object> map = new WeakHashMap<Object, Object>();   
  102.         Object key = new Object();   
  103.         Object value = new Object();   
  104.         map.put(key, value);   
  105.         key = null;   
  106. //        System.out.println("value="+value);   
  107. //        System.out.println("key="+key);   
  108. //        System.out.println("map.containsValue(value)="+map.containsValue(value));  
  109. //        System.out.println("map="+map);   
  110.         System.gc();   
  111.         Thread.sleep(1000);   
  112.         System.out.println("value="+value);   
  113.         System.out.println("key="+key);   
  114.         System.out.println("map.containsValue(value)="+map.containsValue(value));  
  115.         System.out.println("map="+map);   
  116.     }   

原文鏈接:http://www.cnblogs.com/-OYK/archive/2011/10/24/2222874.html

【編輯推薦】

  1. Java程序員慣性思維的一個錯誤
  2. 高手真經(jīng) 13條Java核心技術(shù)
  3. Java的ClassLoader機制解析
  4. 精解Java中代理模式的實現(xiàn)
  5. Java常量池詳解之抓狂的面試題
【責任編輯:小林 TEL:(010)68476606】

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多