Differences and Use Cases of four reference types in java (including theory, code, and execution results)

Source: Internet
Author: User

Differences and Use Cases of four reference types in java (including theory, code, and execution results)

We know that the java language provides four reference types: SoftReference, WeakReference, and PhantomReference, which are closely related to references, there is also a reference queue ReferenceQueue. The relationship between reference and reference queue is very important for garbage collection. To learn about the mechanism of garbage collection, you must first understand how to use the reference queue. This article mainly refers to some theories on the Internet, and works with some of your own test code to better understand these concepts. This blog has also solved the problem.System. gc () and-XX: + DisableExplicitGC startup parameters, and memory release of DirectByteBuffer.


1. Strong references

Strong references will not be recycled by GC, and there is no actual corresponding type in java. lang. ref. Strong references are the most commonly used tools.
Object obj = new Object (); The obj reference here is a strong reference. If an object has a strong reference, it is similar to an essential necessities,The garbage collector will never recycle it.. When the memory space is insufficient, the Java Virtual Machine would rather throw an OutOfMemoryError to terminate the program abnormally and does not recycle strongly referenced objects to solve the problem of insufficient memory.


2. Soft reference

If an object only has soft references, it is similar to the necessities that can be used. IfIf the memory space is sufficient, the garbage collector will not recycle it. If the memory space is insufficient, the memory of these objects will be recycled.. The object can be used by the program only if the garbage collector does not recycle it. Soft references can be used to implement memory-sensitive high-speed cache. Soft references can be used together with a ReferenceQueue, the Java virtual machine adds this soft reference to the reference queue associated with it.

/*** This type of memory is recycled only when the memory is insufficient. Therefore, when the memory is sufficient, it is usually not recycled **
* Whether or not GC is sent, the execution result is: * java. lang. Object @ f9f9d8 * null * java. lang. Object @ f9f9d8 * null *
** It can be seen that only when GC is sent and will be released from memory, JVM will reference the reference if the reference queue */public static void soft () throws Exception {Object obj = new Object (); ReferenceQueueRefQueue = new ReferenceQueue(); SoftReferenceSoftRef = new SoftReference(Obj, refQueue); System. out. println (softRef. get (); // java.lang.Object@f9f9d8System.out.println (refQueue. poll (); // null // clear strong references, triggering GCobj = null; System. gc (); System. out. println (softRef. get (); Thread. sleep (1, 200); System. out. println (refQueue. poll ());}Here are some notes:

1. System. gc () tells JVM that this is a good time to execute GC, but the execution is not decided by JVM (in fact, this Code generally executes GC)

2. Thread. sleep (200); this is because it takes some time to recycle the object to the JVM and add the reference to the refQueue queue. Poll is not a blocking method. If no data exists, null is returned, so we choose to wait for a while.


3. Weak references

If an object only has weak references, it is similar to a necessities that can be used. The difference between weak references and soft references is that only objects with weak references have a shorter life cycle. When the Garbage Collector thread scans the memory area under its jurisdiction,Once an object with weak references is found, its memory will be recycled no matter whether the current memory space is sufficient or not.. However, since the garbage collector is a thread with a low priority, it may not soon find objects with weak references. Weak references can be used together with a ReferenceQueue, the Java virtual machine adds this weak reference to the reference queue associated with it.

/*** Weak reference: When GC occurs, the Weak reference object is always recycled. Therefore, the Weak reference object is easier and faster to be recycled by GC. * Weak reference objects are often used in Map data structures to reference objects that occupy a large amount of memory space **
* If no garbage collection occurs: * java. lang. object @ f9f9d8 * null * java. lang. object @ f9f9d8 * null ** if garbage collection occurs: * java. lang. object @ f9f9d8 * null * java. lang. ref. weakReference @ 422ede **
*/Public static void weak () throws Exception {Object obj = new Object (); ReferenceQueueRefQueue = new ReferenceQueue(); WeakReferenceWeakRef = new WeakReference(Obj, refQueue); System. out. println (weakRef. get (); // java.lang.Object@f9f9d8System.out.println (refQueue. poll (); // null // clear strong references, triggering GCobj = null; System. gc (); System. out. println (weakRef. get (); // note that poll is not blocked and remove is blocked. // It takes some time for JVM to put weak references into the reference queue, So sleep for a while. // System. out. println (refQueue. poll (); // It may be nullThread. sleep (1, 200); System. out. println (refQueue. poll (); // System. out. println (refQueue. poll (); // It must be null because it has been removed from the queue. // System. out. println (refQueue. remove ());}Note the following:

1. remove this is a blocking method, similar to the blocking queue under the J. U. C concurrent package. If there is no queue without data, the current thread remains waiting.

2. If the queue has data, both remove and pool will team the first element.

4. Ghost reference (Virtual Reference)

Virtual references are used to track the activity of objects recycled by the garbage collector. A difference between virtual and soft references and weak references is that virtual references must be used together with the reference Queue (ReferenceQueue. When the garbage collector is preparing to recycle an object, ifWhen it is found that there is a virtual reference, the Virtual Reference will be added to the reference queue associated with it before the object memory is recycled.. The program can determine whether the referenced object has been added to the reference queue to check whether the referenced object is to be recycled. If the program finds that a virtual reference has been added to the reference queue, it can take necessary action before the memory of the referenced object is recycled. Because the Object. finalize () method is insecure and inefficient, virtual references are often used to release resources before the Object is recycled. Refer to my other blog:It is not recommended to explain why finalize is insecure.

/*** When GC 1 discovers a virtual reference object, the PhantomReference object will be inserted into the ReferenceQueue queue. * At this time, the object pointed to by PhantomReference is not recycled by GC, but will not be recycled until the ReferenceQueue is actually processed. **
* If GC is not executed, * null ** GC execution result is: * null * java. lang. ref. phantomReference @ 87816d *
** It is useful to use a virtual cited object before it can be recycled. It is more flexible than the finalize () method */public static void phantom () throws Exception {Object obj = new Object (); ReferenceQueueRefQueue = new ReferenceQueue(); PhantomReferencePhantom = new PhantomReference(Obj, refQueue); System. out. println (phantom. get (); // java.lang.Object@f9f9d8System.out.println (refQueue. poll (); // nullobj = null; System. gc (); // call phanRef. get () will always return nullSystem under any circumstances. out. println (phantom. get (); // when the GC finds a virtual reference, the GC inserts phanRef into the refQueue queue we passed in when we created it. // note that the phanRef references the obj object at this time, it is not recycled by GC. We explicitly call refQueue. after poll returns phanRef, // when the GC detects virtual references for the second time, and then the JVM inserts phanRef into refQueue, the insertion will fail, and GC will recycle the obj Thread. sleep (1, 200); System. out. println (refQueue. poll ());}Note: When the JVM inserts a virtual reference into the reference queue, the object memory of the Virtual Reference execution still exists. However, PhantomReference does not expose the API return object. So if I want to clean up, I need to inherit the PhantomReference class to access the object it points. For example, sun. misc. Cleaner is used for automatic recovery of NIO Direct Memory.

public class Cleaner extends PhantomReference{}
JDK underlying source code query site: http://www.docjar.com/html/api/sun/misc/Cleaner.java.html

References:

Java: Strong, soft, weak, and Virtual Reference http://zhangjunhd.blog.51cto.com/113473/53092/ of Objects

Reference http://www.cnblogs.com/newcj/archive/2011/05/15/2046882.html 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.