1. 程式人生 > >(Four references in java)java中的四種引用

(Four references in java)java中的四種引用

強引用(Strong Reference)

String s = new String(""); //that’s a strong reference
s = null;
功能 :如果一個物件只有強引用,那麼垃圾回收器絕對不會回收它,JVM寧願丟擲記憶體不足的異常也不會回收這些物件. 沒有顯性的釋放物件,JVM時不會回收該物件的.
使用場景 :平時大部分使用的場景都是使用了強引用,比如new建立物件,反射獲得一個物件等
Function:
This kind of reference makes the referenced object not eligible for GC. The JVM would rather throw out an Exception

with Out Of Memory than recycle objects.JVM will recycle this object till the object become null.
Applicition:
Most of the scenes used in peacetime use Strong Reference.For example, get an object through new,or reflect

軟引用(Soft Reference)

Java中提供SoftReference< A >類處理軟引用
功能 :如果一個物件只具有軟引用,則記憶體空間足夠時,垃圾回收器就不會回收它
如果記憶體空間不足時,就會回收這些物件的記憶體.
使用場景 :為了記憶體消耗會選擇使用軟引用,比如快取.
Java provide SoftReference< A > to process soft reference


Function:
if a object only used soft,GC will recycle it till the memory isn’t enough,which means the object will alive based on memory is enough.
Applicition:
In order to consume memory,just like cache.

弱引用(Weak Reference)

java中提供WeakReference類處理弱引用,
功能 :擁有更短的生命週期.只要發生GC,不管記憶體夠不夠,都會進行回收.
使用場景 :用於生命週期更短的,對記憶體更敏感的場景中,比如佔用很大記憶體的Map,java就提供了
WeakHashMap使用,就會使得大Map被即使清理掉
Java provide WeakReference< A > to process weak reference


Function:
Weak has shorter life cycles, if GC happened,no matter memory enough,it will be recycled.
Applicition:
For shorter life cycles,just like Map, java offer WeakHashMap,the big Map will be cleaned up.

虛引用(Phantom Reference)

java中提供PhantomReference類來處
功能 :虛引用形同虛設,與其他幾種引用都不同,虛引用並不會決定物件的生命週期.
那麼它就和沒有引用一樣,在任何時候都有可能被回收.
使用場景 :他的使用場景應該在判斷一個物件是否被垃圾回收了.
Java provide PhantomtReference to process phantom reference
Function:
phantom won’t decide the object’s life cycles,so phantom will be recycled in any time;
*Applicition:
*To judge whether an object is garbage collected.