Four types of references in Java

Source: Internet
Author: User

Starting with the JDK1.2 version, the object's references are divided into four levels, giving the program more flexibility in controlling the object's life cycle. These four levels are high to low in order: Strong references, soft references, weak references, and virtual references.
1. Strong references
The references described earlier in this chapter are actually strong references, which are the most commonly used references. If an object has a strong reference, it is similar to essential necessities, and the garbage collector will never recycle it. When there is not enough memory space, the Java virtual Machine prefers to throw a outofmemoryerror error, which causes the program to terminate abnormally, and does not rely on random recycling of strongly referenced objects to resolve out-of-memory issues.
2. Soft references (SoftReference)
If an object has only soft references, it is similar to a living thing that can be used. If the memory space is sufficient, the garbage collector does not reclaim it, and if the memory space is insufficient, the memory of those objects is reclaimed. The object can be used by the program as long as it is not reclaimed by the garbage collector. Soft references can be used to implement memory-sensitive caches.
A soft reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the soft reference is garbage collected, the Java Virtual machine will add the soft reference to the reference queue associated with it.
3. Weak references (WeakReference)
If an object has only weak references, it is similar to a living thing that can be used. The difference between a weak reference and a soft reference is that an object with only a weak reference has a shorter life cycle. As the garbage collector thread scans the area of memory it governs, once an object with only a weak reference is found, its memory is reclaimed, regardless of whether the current memory space is sufficient or not. However, because the garbage collector is a low-priority thread, it is not necessarily quick to discover objects that have only weak references.
A weak reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the weak reference is garbage collected, the Java virtual machine adds the weak reference to the reference queue associated with it.
4. Virtual Reference (phantomreference)
"Virtual Reference", as the name implies, is a dummy, unlike several other references, a virtual reference does not determine the object's life cycle. If an object holds only virtual references, it can be garbage collected at any time, just as there are no references.

virtual references are primarily used to track the activities of objects that are garbage collected. One difference between a virtual reference and a soft reference and a weak reference is that the virtual reference must be used in conjunction with the reference queue (Referencequeue). When the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory. The program can see if the referenced object is going to be garbage collected by judging whether the reference queue has been added to the virtual reference. If the program finds that a virtual reference has been added to the reference queue, it can take the necessary action before the memory of the referenced object is recycled.



Three classes are available in the Java.lang.ref package: The SoftReference class, the WeakReference class, and the Phantomreference class, which represent soft, weak, and virtual references, respectively. The Referencequeue class represents a reference queue, which can be used in conjunction with these three reference classes in order to track the activity of the object referenced by the Java Virtual machine. The following program creates a string object, a Referencequeue object, and a WeakReference object:
Create a strong reference
String str = new string ("Hello");
Create a reference queue, <String> is a generic tag that indicates that a reference to a String object is held in the queue
Referencequeue<string> RQ = new referencequeue<string> ();
Creates a weak reference that references a "Hello" object and is associated with the RQ reference queue
<String> is a pattern marker, indicating that WeakReference will weakly reference a String object
weakreference<string> wf = new weakreference<string> (str, RQ);
The above program code executes, the in-memory reference is shown in relation to the object in 11-10.


Figure 11-10 "Hello" object has both strong and weak references

in Figure 11-10, an arrow with a solid line represents a strong reference, and a dashed arrow indicates a weak reference. As you can see, the "Hello" object is strongly referenced by STR and is weakly referenced by a WeakReference object, so the "Hello" object is not garbage collected.
in the following program code, set the STR variable that references the "Hello" object to NULL, and then obtain a reference to the "Hello" object by WeakReference The Get () method of the weak reference:
String str = new String (" Hello "); ①
Referencequeue<string> RQ = new referencequeue<string> ();//②
weakreference<string> wf = New Weakreference<string> (str, RQ); ③
Str=null;//④ suppress a strong reference to the "Hello" Object
String str1=wf.get ()//⑤ if the "Hello" object is not reclaimed, str1 references "Hello" object
//if "Hello" The object is not reclaimed, rq.poll () returns null
Reference<? extends string> Ref=rq.poll ();//⑥
After performing the above ④ line, the in-memory reference is shown in relation to object 11-11, at this point The "Hello" object has only a weak reference, so it may be garbage collected. If it has not yet been garbage collected, then the next execution of the Wf.get () method on line ⑤ returns a reference to the "Hello" object and makes the object str1 strongly referenced. The next execution of the Rq.poll () method on line ⑥ returns NULL because there are no references in the reference queue at this time. The Referencequeue poll () method returns a reference in the queue and returns null if none.


Figure 11-11 "Hello" object has only weak references

In the following program code, when you finish line ④, the "Hello" object has only a weak reference. The next two calls the System.GC () method, urging the garbage collector to work, thereby increasing the likelihood that the "hello" object will be recycled. If the "Hello" object is reclaimed, then the reference to the WeakReference object is added to Referencequeue, and the Wf.get () method returns NULL, and the Rq.poll () method returns a reference to the WeakReference object. Figure 11-12 shows the relationship of the in-memory reference to the object after the ⑧ line is executed.
String str = new string ("Hello"); ①
Referencequeue<string> RQ = new referencequeue<string> (); Ii
weakreference<string> wf = new weakreference<string> (str, RQ); ③
Str=null; ④
Two times the garbage collector is urged to work to increase the likelihood of the "hello" object being recycled
System.GC (); ⑤
System.GC (); ⑥
String Str1=wf.get (); ⑦ if the "Hello" object is reclaimed, str1 is null
reference<? Extends string> ref=rq.poll (); ⑧


Figure 11-12 "Hello" object is garbage collected, weak references are added to the reference queue

Here is my relevant test code:

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 (); }}/** strong reference, default implementation of JVM */public static void Test1 () throws interruptedexception {Object obj = new Obje          CT ();          Object strong = obj;          obj = null;          System.GC ();          Thread.Sleep (1000);        System.out.println ("strong=" +strong); /** * [email protected] */}/** * WEakreference Weak reference (when the referenced object no longer has a strong reference within the JVM, the GC weak reference will be automatically reclaimed) * */public static void Test2 () throws Inte          Rruptedexception {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 * */** * Sof Treference SoftReference is basically consistent with WeakReference, the biggest difference is that * SoftReference will keep the reference as long as possible until the JVM is out of memory (Virtual machine Assurance) * *          /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 (Ghost citation) differs greatly from WeakReference and SoftReference * because its get () method always returns NULL * */public static void Test4 () throws Int          Erruptedexception {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 */} /** * Using WeakReference as key, once there is no strong reference to key, * Weakhashmap will automatically delete the relevant * entry */pub after GC Lic 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; ④ a strong reference to the "Hello" object is removed String sTr1=wf.get (); ⑤ if the "Hello" object is not recycled, str1 references the "Hello" object//If the "Hello" object is not reclaimed, rq.poll () returns null SYSTEM.OUT.PRINTLN (Rq.poll ()); ⑥} public static void Test8 () throws interruptedexception {string str = new string ("Hello");//①reference Queue<string> RQ = new referencequeue<string> (); ②weakreference<string> wf = new weakreference<string> (str, RQ); ③str=null; ④ Cancel the strong reference of "Hello" object//two times to urge the garbage collector to work, improve the possibility of "hello" object being recycled System.GC (); ⑤SYSTEM.GC ();    ⑥SYSTEM.GC ();    System.GC ();    System.GC ();    for (int i = 0; i < i++) {System.GC ();} String Str1=wf.get ();     ⑦ if the "Hello" object is reclaimed, str1 is null System.out.println (Rq.poll ()); }}




Four types of references in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.