4 reference differences and usage scenarios in Java (including theory, code, and execution results)

Source: Internet
Author: User

We know that the Java language provides 4 types of references: Strong references, soft references (softreference), weak references (WeakReference), and Ghost References (Phantomreference), which are closely related to references, There is also a reference queue referencequeue. The relationship between reference and reference queues is important for garbage collection, and learning the garbage collection mechanism must first understand how references and reference queues are used. This article mainly refers to some theories on the internet, and with some of their own test code, a better understanding of these concepts. This blog also resolves issues with System.GC () and-XX:+DISABLEEXPLICITGC startup parameters, as well as ghost references left in Directbytebuffer's memory release .


1. Strong references

Strong references are not recycled by GC, and there is no actual corresponding type in Java.lang.ref, and the most work-contact is a strong reference.
Object obj = new Object (); The obj reference here is a strong reference. 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

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.

/** * This kind of memory is only recycled when there is not enough memory, so when memory is sufficient, they are usually not recycled *  * <pre> * Regardless of whether the GC is sent, the result is: * [email protected] * NULL * [email PR  OTECTED] * NULL * </pre> * *  can be seen: only the GC is sent, will be released from memory, the JVM will reference if the reference queue */public static void soft () throws Exception{object obj = new Object (); referencequeue<object> refqueue = new referencequeue<object> (); softreference<object> softref = new softreference<object> (obj, refqueue); System.out.println (Softref.get ()); [Email Protected]system.out.println (Refqueue.poll ());//null//Clear Strong reference, trigger gcobj = null; System.GC (); System.out.println (Softref.get ()); Thread.Sleep (200); System.out.println (Refqueue.poll ());}
Here are a few things to note:

1, System.GC () tells the JVM that this is a good time to perform a GC, but the specific execution is determined by the JVM (in fact, this code generally performs GC)

2, Thread.Sleep (200); This is because it takes a certain amount of time from the object to be reclaimed to the JVM to add the reference to the Refqueue queue. And poll is not a blocking method, and if no data will return NULL, we choose to wait a while.


3. Weak references

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.

/** * Weak reference: When a GC occurs, the weak reference object is always recycled. Therefore weak reference objects are easier and faster to be recycled by GC. * Weak reference objects are often used in map data structures, referencing objects that occupy large memory space * * <pre> * If garbage collection does not occur: * [email protected] * NULL * [Email protec TED] * NULL * * If garbage collection occurs: * [email protected] * NULL * NULL * [email protected] * * <pre> */public Stati c void Weak () throws Exception{object obj = new Object (); referencequeue<object> refqueue = new referencequeue<object> (); weakreference<object> weakRef = new weakreference<object> (obj, refqueue); System.out.println (Weakref.get ()); [Email protected]system.out.println (Refqueue.poll ());//null//Clear Strong reference, trigger gcobj = null; System.GC (); System.out.println (Weakref.get ());//Special note here: The poll is non-blocking, and remove is blocked.//The JVM takes a weak reference into the reference queue for a certain amount of time, so let's sleep for a while/ System.out.println (Refqueue.poll ());//There may be nullthread.sleep (200); System.out.println (Refqueue.poll ());//System.out.println (Refqueue.poll ());//This must be null, since the queue has been removed// System.out.println (Refqueue.remove ());}
Here's what you need to be aware of:

1, remove this is a blocking method, similar to the J.U.C concurrent packet blocking queue, if there is no queue without data, then the front-thread has been waiting.

2, if the queue has data, then Remove and pool will be the first element out of the team.

4. Ghost Reference ( virtual reference )

Virtual references are primarily used to track activities that objects are reclaimed by the garbage collector. 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 discovers 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 reclaimed. Because of the unsafe and inefficient nature of the object.finalize () method, it is common to use virtual references to complete the resource release work before the object is reclaimed. Refer to my other blog: explaining why finalize is unsafe and not recommended

/** * When GC one discovers a virtual reference object, the Phantomreference object is inserted into the Referencequeue queue. * At this point the object pointed to by Phantomreference is not recycled by GC, but is not recycled until referencequeue is processed by you.  * * <pre> * does not occur GC execution result is: * NULL * NULL * NULL * NULL * * Occurs GC execution result is: * NULL * NULL * NULL * [email protected] *  </pre> * * Virtual reference is useful for cleaning operations that must be done before implementing an object is recycled, more flexible than the Finalize () method */public static void Phantom () throws Exception{object obj = new Object (); referencequeue<object> refqueue = new referencequeue<object> (); phantomreference<object> Phantom = new Phantomreference<object> (obj,refqueue); System.out.println (Phantom.get ()); [Email protected]system.out.println (Refqueue.poll ());//nullobj = NULL; System.GC ();//Call Phanref.get () to return NullSystem.out.println (Phantom.get ()) regardless of the circumstances;//When the GC discovers a virtual reference, The GC inserts the PHANREF into the Refqueue queue//Note that we created earlier, when the Obj object referenced by Phanref is not reclaimed by GC, after we explicitly call Refqueue.poll back to Phanref// When the GC finds a virtual reference for the second time, and the JVM inserts phanref into refqueue, the insertion fails, and the GC recycles obj Thread.Sleep (200); System.out.println (Refqueue.poll ());}
In particular, it is important to note that when the JVM inserts a virtual reference into the reference queue, the object memory that the virtual reference executes is still present. But Phantomreference does not expose the API to return objects. So if I want to do cleanup work, I need to inherit the Phantomreference class so that I can access the object it points to. such as the automatic recovery of NiO Direct memory, it is used to the Sun.misc.Cleaner

public class Cleaner extends phantomreference{}
JDK Bottom Source search site: http://www.docjar.com/html/api/sun/misc/Cleaner.java.html

References:

Java: Strong, soft, weak, and virtual references to objects http://zhangjunhd.blog.51cto.com/113473/53092/

Reference http://www.cnblogs.com/newcj/archive/2011/05/15/2046882.html in Java



4 reference differences and usage scenarios in Java (including theory, code, and execution results)

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.