Types Of References In Java : Strong, Soft, Weak And Phantom

轉(zhuǎn)載自:http://javaconceptoftheday.com/types-of-references-in-java-strong-soft-weak-and-phantom/

One of the beauty of the Java language is that it doesn’t put burden of memory management on the programmers. Java automatically manages the memory on the behalf of the programmers. Java programmers need not to worry about freeing the memory after the objects are no more required.Garbage Collector Threaddoes this for you. This?thread is responsible for sweeping out unwanted objects from the memory.?But, you have no control over garbage collector thread. You can’t make it to run whenever you want. It is up to JVM which?decides when to run garbage collector thread.?But, with the introduction ofjava.lang.refclasses, you can have little control over when your objects will be garbage collected.

Depending upon how objects are garbage collected, references to those?objects in java are grouped into 4 types. They are,

1) Strong References

2) Soft References

3) Weak References

4) Phantom References

Let’s discuss these reference types in detail.

1) Strong References

These type of references we use daily while writing the code. Any object in the memory which has?activestrong referenceis not eligible for garbage collection. For example, in the below program, reference variable‘a(chǎn)’is a strong reference which is pointing to class A-type object. At this point of time, this object can’t be garbage collected as it has strong reference.

classA

{

//Class A

}

public class MainClass

{

public static void main(String[] args)

{

A a = new A();//Strong Reference

a = null;//Now, object to which 'a' is pointing earlier is eligible for garbage collection.

}

}

If you make reference‘a(chǎn)’to point to null like in Line 12, then, object to which ‘a(chǎn)’ is pointing earlier will become eligible for garbage collection. Because, it will have no active references pointing to it. This object is most likely to be garbage collected when garbage collector decides to run.

Look at the below picture for more precise understanding.

2) Soft References

The objects which are softly referenced will not be garbage collected (even though they are available for garbage collection) until JVM badly needs memory. These objects will be cleared from the memory only if JVM runs out of memory. You can create a?soft reference to an existing object by usingjava.lang.ref.SoftReferenceclass. Below is the code example on how to create a?soft reference.

classA

{

//A Class

}

publicclassMainClass

{

publicstaticvoidmain(String[] args)

{

A a =newA();//Strong Reference

//Creating Soft Reference to A-type object to which 'a' is also pointing

SoftReference softA =new SoftReference(a);

a =null;//Now, A-type object to which 'a' is pointing earlier is eligible for garbage collection. But, it will be garbage collected only when JVM needs memory.

a = softA.get();//You can retrieve back the object which has been softly referenced

}

}

In the above example, you create two strong references – ‘a‘ and ‘softA‘. ‘a(chǎn)’?is pointing to A-type object and ‘softA’?is pointing to SoftReference type object. This SoftReference type object is internally referring to A-type object to which ‘a(chǎn)’ is also pointing. When ‘a(chǎn)’ is made to point to null, object to which ‘a(chǎn)’ is pointing earlier becomes eligible for garbage collection. But, it will be garbage collected only when JVM needs memory. Because, it is softly referenced by ‘softA’ object.

Look at the below picture for more clarity.

One more use of SoftReference class is that you can retrieve back the object which has been softly referenced. It will?be done by usingget()method. This method returns reference to?the object if object is not cleared from the memory. If object is cleared from the memory, it will return null.

3) Weak References

JVM ignores theweak references. That means objects which has only?week references are eligible for garbage collection. They are likely to be garbage collected when JVM runs garbage collector thread. JVM doesn’t show any regard for weak references.

Below is the code which shows how to create weak references.

classA

{

//A Class

}

publicclassMainClass

{

publicstaticvoidmain(String[] args)

{

A a =newA();//Strong Reference

//Creating Weak Reference to A-type object to which 'a' is also pointing.

WeakReference weakA =new WeakReference(a);

a =null;//Now, A-type object to which 'a' is pointing earlier is available for garbage collection.

a = weakA.get();//You can retrieve back the object which has been weakly referenced.

}

}

Look at the below picture for more clear understanding.

You may think that what is the use of creating weak references

if?they are?ignored by the JVM, Use of weak reference is that you can

retrieve back the weakly referenced object if it is not yet removed from

the memory. This is done using get() method of WeakReference class. It

will return reference to the object if object is not yet removed from

the memory.

4) Phantom References

The objects which are being referenced byphantom referencesare eligible for garbage collection. But, before removing them from the memory, JVM puts them in a queue called‘reference queue’. They are put in a reference queue after calling finalize() method on them. You can’t retrieve back the objects which are being phantom referenced. That means calling get() method on phantom reference always returns null.

Below example shows how to create Phantom References.

classA

{

//A Class

}

publicclassMainClass

{

publicstaticvoidmain(String[] args)

{

A a =newA();//Strong Reference

//Creating ReferenceQueue

ReferenceQueue refQueue =new ReferenceQueue();

//Creating Phantom Reference to A-type object to which 'a' is also pointing

PhantomReference phantomA =new PhantomReference(a, refQueue);

a =null;//Now, A-type object to which 'a' is pointing earlier is available for garbage collection. But, this object is kept in 'refQueue' before removing it from the memory.

a = phantomA.get();//it always returns null

}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市哨颂,隨后出現(xiàn)的幾起案子庭呜,更是在濱河造成了極大的恐慌省容,老刑警劉巖额获,帶你破解...
    沈念sama閱讀 218,451評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異银受,居然都是意外死亡奋岁,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評論 3 394
  • 文/潘曉璐 我一進店門环础,熙熙樓的掌柜王于貴愁眉苦臉地迎上來囚似,“玉大人,你說我怎么就攤上這事线得∪幕剑” “怎么了?”我有些...
    開封第一講書人閱讀 164,782評論 0 354
  • 文/不壞的土叔 我叫張陵贯钩,是天一觀的道長募狂。 經(jīng)常有香客問我办素,道長,這世上最難降的妖魔是什么祸穷? 我笑而不...
    開封第一講書人閱讀 58,709評論 1 294
  • 正文 為了忘掉前任性穿,我火速辦了婚禮,結(jié)果婚禮上粱哼,老公的妹妹穿的比我還像新娘季二。我一直安慰自己,他們只是感情好揭措,可當我...
    茶點故事閱讀 67,733評論 6 392
  • 文/花漫 我一把揭開白布胯舷。 她就那樣靜靜地躺著,像睡著了一般绊含。 火紅的嫁衣襯著肌膚如雪桑嘶。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,578評論 1 305
  • 那天躬充,我揣著相機與錄音逃顶,去河邊找鬼。 笑死充甚,一個胖子當著我的面吹牛以政,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播伴找,決...
    沈念sama閱讀 40,320評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼盈蛮,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了技矮?” 一聲冷哼從身側(cè)響起抖誉,我...
    開封第一講書人閱讀 39,241評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎衰倦,沒想到半個月后袒炉,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,686評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡樊零,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,878評論 3 336
  • 正文 我和宋清朗相戀三年我磁,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片驻襟。...
    茶點故事閱讀 39,992評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡十性,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出塑悼,到底是詐尸還是另有隱情,我是刑警寧澤楷掉,帶...
    沈念sama閱讀 35,715評論 5 346
  • 正文 年R本政府宣布厢蒜,位于F島的核電站霞势,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏斑鸦。R本人自食惡果不足惜愕贡,卻給世界環(huán)境...
    茶點故事閱讀 41,336評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望巷屿。 院中可真熱鬧固以,春花似錦、人聲如沸嘱巾。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽旬昭。三九已至篙螟,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間问拘,已是汗流浹背遍略。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留骤坐,地道東北人绪杏。 一個月前我還...
    沈念sama閱讀 48,173評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像纽绍,于是被迫代替她去往敵國和親蕾久。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,947評論 2 355

推薦閱讀更多精彩內(nèi)容