標籤:
從JDK1.2版本開始,把對象的引用分為四種層級,從而使程式能更加靈活的控制對象的生命週期。這四種層級由高到低依次為:強引用、軟引用、弱引用和虛引用。
1.強引用
本章前文介紹的引用實際上都是強引用,這是使用最普遍的引用。如果一個對象具有強引用,那就 類似於必不可少的生活用品,記憶體回收行程絕不會回收它。當記憶體空 間不足,Java虛擬機器寧願拋出OutOfMemoryError錯誤,使程式異常終止,也不會靠隨意回收具有強引用的對象來解決記憶體不足問題。
2.軟引用(SoftReference)
如果一個對象只具有軟引用,那就類似於可有可物的生活用品。如果記憶體空間足夠,記憶體回收行程就不會回收它,如果記憶體空間不足了,就會回收這些對象的記憶體。只要記憶體回收行程沒有回收它,該對象就可以被程式使用。軟引用可用來實現記憶體敏感的快取。
軟引用可以和一個引用隊列(ReferenceQueue)聯合使用,如果軟引用所引用的對象被記憶體回收,Java虛擬機器就會把這個軟引用加入到與之關聯的引用隊列中。
3.弱引用(WeakReference)
如果一個對象只具有弱引用,那就類似於可有可物的生活用品。 弱引用與軟引用的區別在於:只具有弱引用的對象擁有更短暫的生命週期。在記憶體回收行程線程掃描它 所管轄的記憶體地區的過程中,一旦發現了只具有弱引用的對象,不管當前記憶體空間足夠與否,都會回收它的記憶體。不過,由於記憶體回收行程是一個優先順序很低的線程, 因此不一定會很快發現那些只具有弱引用的對象。
弱引用可以和一個引用隊列(ReferenceQueue)聯合使用,如果弱引用所引用的對象被記憶體回收,Java虛擬機器就會把這個弱引用加入到與之關聯的引用隊列中。
4.虛引用(PhantomReference)
"虛引用"顧名思義,就是形同虛設,與其他幾種引用都不同,虛引用並不會決定對象的生命週期。如果一個對象僅持有虛引用,那麼它就和沒有任何引用一樣,在任何時候都可能被記憶體回收。
虛引用主要用來跟蹤對象被記憶體回收的活動。虛引用與軟引用和弱引用的一個區別在於:虛引用必須和引用隊列(ReferenceQueue)聯合使用。當垃 圾回收器準備回收一個對象時,如果發現它還有虛引用,就會在回收對象的記憶體之前,把這個虛引用加入到與之關聯的引用隊列中。程式可以通過判斷引用隊列中是 否已經加入了虛引用,來瞭解被引用的對象是否將要被記憶體回收。程式如果發現某個虛引用已經被加入到引用隊列,那麼就可以在所引用的對象的記憶體被回收之前採取必要的行動。
在java.lang.ref包中提供了三個類:SoftReference類、WeakReference類和PhantomReference 類,它 們分別代表軟引用、弱引用和虛引用。ReferenceQueue類表示引用隊列,它可以和這三種引用類聯合使用,以便跟蹤Java虛擬機器回收所引用的對 象的活動。以下程式建立了一個String對象、ReferenceQueue對象和WeakReference對象:
//建立一個強引用
String str = new String("hello");
//建立引用隊列, <String>為範型標記,表明隊列中存放String對象的引用
ReferenceQueue<String> rq = new ReferenceQueue<String>();
//建立一個弱引用,它引用"hello"對象,並且與rq引用隊列關聯
//<String>為範型標記,表明WeakReference會弱引用String對象
WeakReference<String> wf = new WeakReference<String>(str, rq);
以上程式碼執行完畢,記憶體中引用與對象的關係11-10所示。
圖11-10 "hello"對象同時具有強引用和弱引用
在圖11-10中,帶實線的箭頭表示強引用,帶虛線的箭頭表示弱引用。可以看出,此時"hello"對象被str強引用,並且被一個WeakReference對象弱引用,因此"hello"對象不會被記憶體回收。
在以下程式碼中,把引用"hello"對象的str變數置為null,然後再通過WeakReference弱引用的get()方法獲得"hello"對象的引用:
String str = new String("hello"); //①
ReferenceQueue<String> rq = new ReferenceQueue<String>(); //②
WeakReference<String> wf = new WeakReference<String>(str, rq); //③
str=null; //④取消"hello"對象的強引用
String str1=wf.get(); //⑤假如"hello"對象沒有被回收,str1引用"hello"對象
//假如"hello"對象沒有被回收,rq.poll()返回null
Reference<? extends String> ref=rq.poll(); //⑥
執行完以上第④行後,記憶體中引用與對象的關係11-11所示,此 時"hello"對象僅僅具有弱引用,因此它有可能被記憶體回收。假如它還沒有被記憶體回收,那麼接下來在第⑤行執行wf.get()方法會返 回"hello"對象的引用,並且使得這個對象被str1強引用。再接下來在第⑥行執行rq.poll()方法會返回null,因為此時引用隊列中沒有任 何引用。ReferenceQueue的poll()方法用於返回隊列中的引用,如果沒有則返回null。
圖11-11 "hello"對象只具有弱引用
在以下程式碼中,執行完第④行後,"hello"對象僅僅具有弱引用。接下來兩次調用System.gc()方法,催促記憶體回收行程工作,從而提 高"hello"對象被回收的可能性。假如"hello"對象被回收,那麼WeakReference對象的引用被加入到ReferenceQueue 中,接下來wf.get()方法返回null,並且rq.poll()方法返回WeakReference對象的引用。圖11-12顯示了執行完第⑧行後 記憶體中引用與對象的關係。
String str = new String("hello"); //①
ReferenceQueue<String> rq = new ReferenceQueue<String>(); //②
WeakReference<String> wf = new WeakReference<String>(str, rq); //③
str=null; //④
//兩次催促記憶體回收行程工作,提高"hello"對象被回收的可能性
System.gc(); //⑤
System.gc(); //⑥
String str1=wf.get(); //⑦ 假如"hello"對象被回收,str1為null
Reference<? extends String> ref=rq.poll(); //⑧
圖11-12 "hello"對象被記憶體回收,弱引用被加入到引用隊列
下面是我的相關測試代碼:
package dhp;import java.lang.ref.PhantomReference;import java.lang.ref.ReferenceQueue;import java.lang.ref.SoftReference;import java.lang.ref.WeakReference;import java.util.Map;import java.util.WeakHashMap;public class Ref { public Ref() { } /** * @param args */ public static void main(String[] args) { try { //test1(); //test2(); //test3(); //test4(); //test5(); //test6(); //test7(); test8(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** 強引用,JVM的預設實現 */ public static void test1() throws InterruptedException { Object obj = new Object(); Object strong = obj; obj = null; System.gc(); Thread.sleep(1000); System.out.println("strong="+strong); /** * [email protected] */ } /** * WeakReference 弱引用( 當所引用的對象在 JVM 內不再有強引用時, GC 後weak reference 將會被自動回收) * */ public static void test2() throws InterruptedException { Object obj = new Object(); WeakReference<Object> wr = new WeakReference<Object>(obj); obj = null; System.gc(); Thread.sleep(1000); System.out.println("wr.get()="+wr.get()); System.out.println("wr="+wr); wr.clear(); System.out.println("w1111r="+wr.get()); /** * wr.get()=null [email protected] w1111r=null */ } /** * SoftReference SoftReference 於 WeakReference 的特性基本一致, 最大的區別在於 * SoftReference 會儘可能長的保留引用直到 JVM 記憶體不足時才會被回收(虛擬機器保證) * */ public static void test3() throws InterruptedException { Object obj = new Object(); SoftReference<Object> sr = new SoftReference<Object>(obj); obj = null; System.gc(); Thread.sleep(1000); System.out.println("sr.get()="+sr.get()); /** * sr.get()[email protected] */ } /** * PhantomReference Phantom Reference(幽靈引用) 與 WeakReference 和 SoftReference * 有很大的不同, 因為它的 get() 方法永遠返回 null * */ public static void test4() throws InterruptedException { Object obj = new Object(); ReferenceQueue<Object> rq = new ReferenceQueue<Object>(); PhantomReference<Object> pr = new PhantomReference<Object>(obj, rq); System.out.println("pr.get()="+pr.get()); /** * pr.get()=null */ } /** * ReferenceQueue: * @throws InterruptedException */ public static void test5() throws InterruptedException { Object obj = new Object(); ReferenceQueue<Object> rq = new ReferenceQueue<Object>(); WeakReference<Object> pr = new WeakReference<Object>(obj, rq); System.out.println("**pr.enqueue()="+pr.enqueue()); System.out.println("**pr.isEnqueued()="+pr.isEnqueued()); System.out.println("**pr="+pr); System.out.println("**rq.poll()="+rq.poll()); obj = null; System.out.println("======================="); System.gc(); System.out.println("pr.enqueue()="+pr.enqueue()); System.out.println("**pr.isEnqueued()="+pr.isEnqueued()); System.out.println("pr="+pr); System.out.println("rq.poll()="+rq.poll()); System.out.println("obj5="+obj); /** * **pr.enqueue()=true**pr.isEnqueued()=true**[email protected]**rq.poll()[email protected]=======================pr.enqueue()=false**pr.isEnqueued()=false[email protected]rq.poll()=nullobj5=null */ } /** * 使用 WeakReference 作為 key, 一旦沒有指向 key 的強引用, * WeakHashMap 在 GC 後將自動刪除相關的 * entry */ public static void test6() throws InterruptedException { Map<Object, Object> map = new WeakHashMap<Object, Object>(); Object key = new Object(); Object value = new Object(); map.put(key, value); key = null; // System.out.println("value="+value); // System.out.println("key="+key); // System.out.println("map.containsValue(value)="+map.containsValue(value)); // System.out.println("map="+map); System.gc(); Thread.sleep(1000); System.out.println("value="+value); System.out.println("key="+key); System.out.println("map.containsValue(value)="+map.containsValue(value)); System.out.println("map="+map); } public static void test7() throws InterruptedException { String str = new String("hello"); //① ReferenceQueue<String> rq = new ReferenceQueue<String>(); //② WeakReference<String> wf = new WeakReference<String>(str, rq); //③ str=null; //④取消"hello"對象的強引用 String str1=wf.get(); //⑤假如"hello"對象沒有被回收,str1引用"hello"對象 //假如"hello"對象沒有被回收,rq.poll()返回null System.out.println(rq.poll()); //⑥ } public static void test8() throws InterruptedException { String str = new String("hello"); //① ReferenceQueue<String> rq = new ReferenceQueue<String>(); //② WeakReference<String> wf = new WeakReference<String>(str, rq); //③ str=null; //④取消"hello"對象的強引用 //兩次催促記憶體回收行程工作,提高"hello"對象被回收的可能性 System.gc(); //⑤ System.gc(); //⑥ System.gc(); System.gc(); System.gc(); for (int i = 0; i < 10; i++) { System.gc();} String str1=wf.get(); //⑦ 假如"hello"對象被回收,str1為null System.out.println(rq.poll()); }}
Java中四種引用