Java strong references, soft references, weak references, virtual references

Source: Internet
Author: User


Statement ***********************
********************* **********

Original works, from the "Xiaofeng Moon XJ" blog, Welcome to reprint, please be sure to indicate the source (HTTP://BLOG.CSDN.NET/XIAOFENGCANYUEXJ).

Due to various reasons, there may be many shortcomings, welcome treatise!

*************** ******************************************************************************************

There is no concept of pointers in Java, and references are a weakening pointer to ensure that development cannot manipulate memory arbitrarily. Recently sorted out the various level references that were not understood before: strong references, soft references, weak references, virtual references, and their features and scenarios are summarized as follows:

1. Strong references
If an object has a strong reference, the GC will never recycle it, and when there is not enough memory, the JVM prefers to throw a outofmemoryerror error. Generally new objects are strong references, as follows

Strong reference to User Strangereference=new user ();

2. Soft reference
If an object has soft references, when there is not enough memory space, the GC reclaims the memory of those objects and uses soft references to build the cache of sensitive data.

In the JVM, a soft reference is defined as follows, which can be reclaimed by a timestamp, which is quoted here as the JVM:

public class Softreference<t> extends reference<t> {/** * Timestamp clock, updated by the garbage Coll    Ector * * Static private long clock;  /** * Timestamp updated by each invocation of the Get method.     The VM may use * This field if selecting soft references to being cleared, but it's not * required-do.    */private long timestamp;  /** * Creates a new soft reference that refers to the given object.     The new * Reference is not a registered with any queue. * * @param referent Object The new soft reference would refer to */public softreference (T referent) {su        Per (referent);    This.timestamp = clock;     }/** * Creates a new soft reference that refers to the given object and are * registered with the given queue. * * @param referent Object The new soft reference would refer to * @param q the queue with which the reference IS-to-be registered, * or <tt>null</tt&Gt        If registration is not required * */public SoftReference (T referent, referencequeue<? Super T> Q) {        Super (referent, q);    This.timestamp = clock;  }/** * Returns This Reference object ' s referent.  If this Reference object have * been cleared, either by the program or by the garbage collector, then * this method     returns &LT;CODE&GT;NULL&LT;/CODE&GT;. * * @return The object to which this reference refers, or * <code>null</code> if this Refe        Rence object has been cleared */public T get () {t o = super.get ();        if (o! = null && this.timestamp! = clock) This.timestamp = clock;    return o; }}
With a strong reference or anonymous object for the declaration of a soft reference, a strong reference can be obtained through the Get method using the generic softreference<t>;. Specific as follows:

Soft reference softreference<user>softreference=new softreference<user> (New User ()); strangereference= Softreference.get ();//Get strong references by Get method


3. Weak references
If an object has a weak reference, in the process of scanning the memory area by the GC thread, the memory is reclaimed regardless of the current memory space, and a weak reference is used to build the cache of the non-sensitive data.

In the JVM, a weak reference is defined as follows from the JVM:

public class Weakreference<t> extends reference<t> {    /**     * Creates a new weak Reference this refers to The given object.  The new * Reference is not a registered with any     queue.     *     * @param referent Object The new weak reference would refer to     *    /Public weakreference (T referent) {        Supe R (referent);    }    /**     * Creates a new weak reference that refers to the given object and are     * registered with the given QUEUE.
   *     * @param referent Object The new weak reference would refer to     * @param q the queue with which the reference IS-to-be registered,     *          or <tt>null</tt> If registration are not required     *    /Public WeakReference (T referent, referencequeue<? Super T> Q) {        super (referent, q);    }}

use a strong reference or an anonymous object for a weak-referencing declaration, using the generic Weakreference<t>, as follows:

Weak reference weakreference<user>weakreference=new weakreference<user> (New User ());

4. Virtual Reference
If an object holds only virtual references and can be garbage collected at any time, 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 and the virtual reference is used primarily to track the object's garbage collection activity.

In the JVM, a virtual reference is defined as follows from the JVM:

public class Phantomreference<t> extends reference<t> {/** * Returns this Reference object ' s referent. Because the referent of A * Phantom reference is always inaccessible, this method always returns * <code>n     Ull</code>.    * * @return <code>null</code> * * Public T get () {return null; }/** * Creates a new Phantom reference that refers to the given object and * are registered with the given Queu E. * * <p> It is possible to create a phantom reference with a <tt>null</tt> * queue, but Su  Ch A reference is completely useless:its <tt>get</tt> * method would always return null and, since it does     Not having a queue, it * would never be enqueued. * * @param referent The object The new Phantom reference would refer to * @param q the queue with which the Referen Ce is-to-be registered, * or <tt>null</tt> if registration are not required */Public phantomreference (T referent, referencequeue<? Super T> Q) {super (referent, q); }}
The declaration of a virtual reference phantomreference<t> with a strong reference or an anonymous object, in conjunction with the generic referencequeue<t> initialization, as follows:
Virtual reference phantomreference<user> phantomreference=new phantomreference<user> (New User (), New ReferenceQueue <User> ());


5. Summary

Here is a program about strong references, soft references, weak references, and virtual references:

Import Java.lang.ref.*;import Java.util.hashset;import java.util.set;class User {private String name;    Public user () {} public User (String name) {this.name=name;    } @Override Public String toString () {return name; } public void Finalize () {System.out.println ("finalizing ...    "+name); }}/** * Created by Jinxu on 15-4-25. */public class Referencedemo {private static referencequeue<user> Referencequeue = new Referencequeue<user&gt    ;();    private static final int size = 10;        public static void Checkqueue () {/* REFERENCE&LT;? extends user> Reference = null;        while ((reference = Referencequeue.poll ())!=null) {System.out.println ("in Queue:" +reference.get ()); }*/reference<?        Extends user> reference = Referencequeue.poll ();        if (reference!=null) {System.out.println ("in Queue:" +reference.get ()); }} public static void Testsoftreference () {Set<softreference<user>> softreferenceset = new hashset<softreference<user>> (); for (int i = 0; i < size; i++) {softreference<user> ref = new Softreference<user> ("Sof            T "+ i), referencequeue);            System.out.println ("Just created:" + ref.get ());        Softreferenceset.add (ref);        } System.GC ();    Checkqueue (); } public static void Testweakreference () {set<weakreference<user>> weakreferenceset = new Hashse        T<weakreference<user>> (); for (int i = 0; i < size; i++) {weakreference<user> ref = new Weakreference<user> (The new User ("Wea            K "+ i), referencequeue);            System.out.println ("Just created:" + ref.get ());        Weakreferenceset.add (ref);        } System.GC ();    Checkqueue (); } public static void Testphantomreference () {set<phantomreference<user>> Phantomreferenceset =New Hashset<phantomreference<user>> (); for (int i = 0; i < size; i++) {phantomreference<user> ref = new phantomreference& Lt            User> (New User ("Phantom" + i), referencequeue);            System.out.println ("Just created:" + ref.get ());        Phantomreferenceset.add (ref);        } System.GC ();    Checkqueue ();        } public static void Main (string[] args) {testsoftreference ();        Testweakreference ();    Testphantomreference (); }}

result is

Just created:soft 0Just created:soft 1Just created:soft 2Just created:soft 3Just created:soft 4Just created:soft 5Ju  St Created:soft 6Just created:soft 7Just created:soft 8Just created:soft 9Just created:weak 0Just created:weak 1Just Created:weak 2Just created:weak 3Just created:weak 4Just created:weak 5Just created:weak 6Just created:weak 7Just C Reated:weak 8Just created:weak 9Finalizing ... Weak 7Finalizing ... Weak 8Finalizing ... Weak 9Finalizing ... Weak 4Finalizing ... Weak 5Finalizing ... Weak 6Finalizing ... Weak 0Finalizing ... Weak 1Finalizing ... Weak 2Finalizing ... Weak 3Finalizing ... Soft 9Finalizing ... Soft 8Finalizing ... Soft 7Finalizing ... Soft 6Finalizing ... Soft 5Finalizing ... Soft 4Finalizing ... Soft 3Finalizing ... Soft 2Finalizing ... Soft 1Finalizing ... Soft 0In queue:nulljust created:nulljust created:nulljust created:nulljust created:nulljust created:nulljust Create D:nulljust Created:nulljust Created:nulljust Created:nulljusT Created:nullin queue:nullfinalizing ... Phantom 9Finalizing ... Phantom 7Finalizing ... Phantom 8Finalizing ... Phantom 4Finalizing ... Phantom 5Finalizing ... Phantom 6Finalizing ... Phantom 0Finalizing ... Phantom 1Finalizing ... Phantom 2Finalizing ... Phantom 3


As can be seen from the running results of the program, the virtual reference is a dummy, the object it refers to can be reclaimed by the garbage collector at any time, the object with the weak reference has a slightly longer life cycle, when the garbage collector performs the reclamation, it may be reclaimed by the garbage collector, the object with soft reference has a longer life cycle, However, when the Java Virtual machine considers that the memory is low, it is also recycled by the garbage collector.


due to the limited time, in the process of writing a few references to some of the literature, thank you, at the same time, given the level of reasons, you inevitably have shortcomings, welcome treatise!

Java strong references, soft references, weak references, virtual references

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.