Summarize and analyze four common 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 Reference (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 references (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.

In this book, "References" can be both verbs and nouns, and the reader should differentiate the meaning of "references" according to the context.

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 to track the activity of the referenced objects 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");

Creates a reference queue, which is a generic tag that indicates that a reference to a string object is held in the queue

Referencequeue RQ = new Referencequeue ();

Creates a weak reference that references a "Hello" object and is associated with the RQ reference queue

As a pattern marker, indicates that WeakReference will weakly reference a string object weakreference wf = new WeakReference (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 RQ = new Referencequeue ();

②weakreference wf = new WeakReference (str, RQ);

③str=null; ④ a strong reference to the "Hello" object, 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 Reference Ref=rq.poll ();

After executing line ④ above, the in-memory reference is shown in relation to object 11-11, at which 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 this object str1 strong references. 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 to the System.GC () method, urging the garbage collector to work, thus increasing the likelihood that the "hello" object will be recycled. If the "Hello" object is recycled, Then the reference to the WeakReference object is added to the Referencequeue, and the next Wf.get () method returns NULL, and the Rq.poll () method returns a reference to the WeakReference object. Figure 11-12 shows the end of line ⑧ after execution An in-memory reference to the object's relationship.

String str = new string ("Hello");

①referencequeue RQ = new Referencequeue ();

②weakreference wf = new WeakReference (str, RQ);

③str=null;

④//two times to urge the garbage collector to work, increasing the likelihood of "hello" objects being recycled System.GC ();

⑤SYSTEM.GC ();

⑥string Str1=wf.get ();

⑦ if the "Hello" object is recycled, str1 is null Reference ref=rq.poll ();

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

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

Package com. Testref; 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 ();

} 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 Object ();

Object strong = obj;

obj = null;

System.GC ();

Thread.Sleep (1000);

System.out.println ("strong=" +strong);

}

/**

* WeakReference Weak references (GC weak reference will be automatically reclaimed when the referenced object no longer has a strong reference within the JVM)

* */

public static void Test2 () throws Interruptedexception {

Object obj = new Object ();

WeakReference wr = new WeakReference (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 ());

}

/**

* The characteristics of SoftReference softreference in WeakReference are basically the same, the biggest difference is

* SoftReference will keep references 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 sr = new SoftReference (obj);

obj = null;

System.GC ();

Thread.Sleep (1000);

System.out.println ("sr.get () =" +sr.get ());

}

/**

* Phantomreference Phantom Reference (Ghost citation) with WeakReference and SoftReference

* There is a big difference because its get () method always returns null

* */

public static void Test4 () throws Interruptedexception {

Object obj = new Object ();

Referencequeue RQ = new Referencequeue ();

Phantomreference PR = new phantomreference (obj, RQ);

System.out.println ("pr.get () =" +pr.get ());

}

/**

* Referencequeue:

* @throws interruptedexception

*/

public static void Test5 () throws Interruptedexception {

Object obj = new Object ();

Referencequeue RQ = new Referencequeue ();

WeakReference PR = new WeakReference (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.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);

}

/**

* Using WeakReference as key, once there is no strong reference to key,

* Weakhashmap after GC will automatically delete the relevant

* 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=http://developer.51cto.com/art/201111/" +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=http://developer.51cto.com/art/201111/" +value);

System.out.println ("key=" +key);

System.out.println ("map.containsvalue (value) =" +map.containsvalue (value));

System.out.println ("map=" +map);

}

}

Summarize and analyze four common types of references in Java

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.