Reference in Java

Source: Internet
Author: User

In jdk 1.2 and later versions, four concepts were introduced: strong reference, soft reference, weak reference, and virtual reference. There are a lot of explanations on these four concepts on the Internet, but most of them are general concepts. Today I have analyzed them with the Code. First, let's look at the definition and general explanation (the reference type is in the java package. lang. in ref ).

1. StrongReference)

Strong references will not be recycled by GC, and there is no actual corresponding type in java. lang. ref. For example:
Object obj = new Object ();
The obj reference here is a strong reference and won't be recycled by GC.

2. Soft reference)

Soft references are collected by GC only when the JVM reports that the memory is insufficient. Otherwise, they are not recycled. It is precisely because of this feature that soft references are widely used in caching and pooling. Usage of soft reference:

Object obj = new Object (); SoftReference <Object> softRef = new SoftReference (obj); // use softRef. get () gets the Object objg = softRef referenced by the soft reference. get ();

3. WeakReference)

When GC 1 discovers a weak reference object, it will release the object referenced by WeakReference. The usage of weak references is similar to that of soft references, but the recycling policy is different.

4. PhantomReference)

When GC 1 discovers a virtual reference object, it will insert the PhantomReference object into the ReferenceQueue queue. At this time, the object pointed to by PhantomReference is not recycled by GC, instead, it will not be recycled until the ReferenceQueue is processed by you. Usage of virtual references:

Object obj = new Object (); ReferenceQueue <Object> refQueue = new ReferenceQueue <Object> (); PhantomReference <Object> phanRef = new PhantomReference <Object> (obj, refQueue ); // call phanRef. get () will always return nullObject objg = phanRef no matter under any circumstances. get (); // If obj is set to null, GC inserts phanRef into the refQueue queue passed in when GC discovers a virtual reference. // note that, in this case, the obj object referenced by phanRef is not recycled by GC. We explicitly call refQueue. after poll returns phanRef, // when the GC finds a Virtual Reference for the second time, and the JVM inserts phanRef into refQueue, the insert will be lost. If it fails, GC will recycle the Reference object. <? Extends Object> phanRefP = refQueue. poll ();

After reading the simple definition, we can use the code to test it. Strong references do not need to be mentioned. The soft references are also clearly described, the key is "weak reference" and "Virtual Reference ".

Weak reference:

public static void main(String[] args) throws InterruptedException {Object obj = new Object();ReferenceQueue<Object> refQueue = new ReferenceQueue<Object>();WeakReference<Object> weakRef = new WeakReference<Object>(obj, refQueue);System.out.println(weakRef.get());System.out.println(refQueue.poll());obj = null;System.gc();System.out.println(weakRef.get());System.out.println(refQueue.poll());}

Because System. gc () is a good time to tell JVM that it is a good time to execute GC, but the execution is not decided by JVM. Therefore, when JVM decides to execute GC, the result is (in fact, this code usually executes GC ):

Java. lang. Object @ de6ced
Null
Null
Java. lang. ref. WeakReference @ 1fb8ee3

According to the execution result, weakRef is called. get () We get the obj object. Because GC is not executed, refQueue. null returned by poll (). When obj = null is taken, no reference is directed to the obj object in the heap. Here, the JVM executes a GC, and we use weakRef. get () returns null, while refQueue. poll () returns the WeakReference object. Therefore, after the JVM recycles obj, it inserts weakRef into the refQueue queue.

Virtual Reference:

public static void main(String[] args) throws InterruptedException {Object obj = new Object();ReferenceQueue<Object> refQueue = new ReferenceQueue<Object>();PhantomReference<Object> phanRef = new PhantomReference<Object>(obj, refQueue);System.out.println(phanRef.get());System.out.println(refQueue.poll());obj = null;System.gc();System.out.println(phanRef.get());System.out.println(refQueue.poll());}

Similarly, when the JVM executes GC, the result is:

Null
Null
Null
Java. lang. ref. PhantomReference @ 1fb8ee3

According to the execution results, what we mentioned earlier is no error, phanRef. get () returns null under any circumstances. After JVM executes GC and finds a virtual reference, the JVM does not recycle obj, instead, insert the PhantomReference object to the corresponding Virtual Reference queue refQueue. When refQueue is called. when poll () returns a PhantomReference object, the poll method first sets the queue (ReferenceQueue <? Super T>) is set to NULL. The NULL object inherits from ReferenceQueue and overwrites the enqueue (Reference paramReference) method to return false. When obj is detected by GC again, JVM inserts PhantomReference into the NULL queue and returns false if insertion fails. GC then recycles obj. In fact, we can't see whether obj is recycled through this code, but the javadoc comment of PhantomReference is written like this:

Once the garbage collector decides that an objectobjIs phantom-reachable, it is being enqueued on the corresponding queue, but its referent is not cleared. That is, the reference queue of the phantom reference must explicitly be processed by some application code.

(This sentence is very simple. I believe many people can understand it as well ):

Once GC determines that an "obj" is virtual accessible, it (PhantomReference) will be queued to the corresponding queue, but it is not cleared. That is to say, the reference queue of virtual references must be explicitly processed by some application code.

Use of weak references and virtual references

Soft references can obviously be used to create caching and pooling. What about weak references and virtual references? In fact, it is also very useful. First, let's look at the weak references. For example:

 class Registry {     private Set registeredObjects = new HashSet();     public void register(Object object) {         registeredObjects.add( object );     } }

All objects added to registeredObjects will never be recycled by GC, because there is a strong reference stored in registeredObjects. If I change the code to the following:

class Registry {     private Set registeredObjects = new HashSet();     public void register(Object object) {         registeredObjects.add( new WeakReference(object) );     } }

Now, If GC wants to recycle the objects in registeredObjects, it can be implemented. Similarly, if HashMap is used to achieve the above effect, a better implementation is to use WeakHashMap.

What about virtual references? Let's take a look at some of the javadoc instructions:

Phantom references are useful for implementing cleanup operations that are necessary before an object gets garbage-collected. They are sometimes more flexible thanfinalize()Method.

Translation:

It is useful to use a virtual index to clear objects before they are recycled. Sometimes they are more flexible than the finalize () method.

Obviously, virtual references can be used to clear objects before they are recycled.

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.