Java: The difference between strong, soft, weak, and virtual references to objects

Source: Internet
Author: User

1 . Strong, soft, weak, and virtual references to objects In Previous versions of JDK 1.2, if an object was not referenced by any variable, the program could no longer use the object. That is, only the object is in the accessible (reachable) state before the program can use it. Starting with JDK version 1.2, the reference to the object is divided into 4 levels, giving the program more flexibility in controlling the object's life cycle. These 4 levels are from highest to lowest: Strong references, soft references, weak references, and virtual reference times. ⑴ Strong references (strongreference)strong references are the most commonly used references. If an object has a strong reference, 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. ⑵ Soft Reference (SoftReference)if an object has only soft references, enough memory space is available, the garbage collector does not recycle 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 (see below for an example). a soft reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the soft reference is reclaimed by the garbage collector, the Java Virtual machine will add the soft reference to the reference queue associated with it. ⑶ Weak references (weakreference)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. ⑷ 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 reclaimed by the garbage collector at any time, just as there are no references. 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. 2 . Weakly referenced and virtual-referenced particles (1) Weak references
Import Java.lang.ref.weakreference;public class Referencetest {public static void main (string[] args) {// Create a String object, String str = new String ("I love to learn Java");//Create a weak reference to refer to the "I love to learn Java" string WeakReference wr = new WeakReference (str);// Cut off Str and I love to learn the references between Java strings str = null;//Remove objects referenced by weak references System.out.println (Wr.get ());//Forced Garbage collection System.GC ();// Call the Finalize Method System.runfinalization ();//Remove the weakly referenced object System.out.println (Wr.get ()) again;//============================== ===================================object obj = Wr.get (), if (obj = = null) {//Rebuilds a WR = new WeakReference (Recreateit ()); OB J =wr.get (); System.out.println (obj);} Cut the obj =null again; System.out.println (obj);} Private static Object Recreateit () {String str = new String ("New Strings Object"); return str;}}

  (2) Virtual reference

Import Java.lang.ref.phantomreference;import Java.lang.ref.referencequeue;import java.lang.ref.WeakReference; public class Phantomreferencetest {public static void main (string[] args) {//Create a String object, String str = new String ("I love learning Java"); Create a reference queue Referencequeue RQ = new Referencequeue ();//Create a virtual reference, let the virtual reference refer to "I love learning java" phantomreference PR = new Phantomreferenc E (str, RQ);//Cut STR and I love to learn the references between Java strings str = null;//does not get the referenced object through a virtual reference, the output is NullSystem.out.println (Pr.get ());// Forced garbage collection System.GC ();//Call Finalize Method System.runfinalization ();//After garbage collection, the virtual reference will be placed in the reference queue// Take out the reference queue first to enter the queue reference to compare with the PR System.out.println (rq.poll () = = PR);}}

  

Java: The difference between strong, soft, weak, and virtual references to objects

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.