Brief analysis of Java Reference__java

Source: Internet
Author: User

Java1.2 introduces a new concept--reference, which is the default strong reference, that is, strong Reference. In the GC process, as long as the path can be reached from GC roots through strong references, then the next program may be used, it can not be recycled, and vice versa.
But this approach is more rigid, in order to increase the flexibility of garbage collection there is the Java.lang.ref class library, which contains the most important abstract class reference, and its three inheritance classes: SoftReference (soft reference), WeakReference (weak reference) and Phantomreference (Phantom Reference). When the object being examined by the garbage collector can only be obtained through one of the three reference objects, the three reference derived classes give a different indication to the GC: when the JVM reports low memory, All objects that are only pointed to by SoftReference are collected by GC, or they are not recycled; When the GC discovers that an object can only be reached through a weakly referenced object, the object referenced by WeakReference is released. When the GC discovers an object can only be reached by Phantom Reference object, The Phantomreference object will be inserted into its associated referencequeue queue (the initialization of the Phantomreference object must have a referencequeue queue). At this point, the object that phantomreference is pointing to only executes the Finalize method, but the object itself is not collected by GC, and will not be reclaimed until the referencequeue is actually processed, such as by calling the Remove method.

So how did the above function be done? Below the use of JDK source code simple analysis:
In the reference class, there is a domain referent used to hold references to the object being referred to:

Private T referent;

/*-Constructors-*/

Reference (T referent) {This
    (referent, null);
}

Reference (T referent, referencequeue< Super t> queue) {
    this.referent = referent;
    This.queue = (queue = null)? ReferenceQueue.NULL:queue;
}

When the reference object is initialized, referent points to the object that is passed in. When a GC finds that the target object has only the referent point in the Reference object, the recycle policy is executed according to the three rules above. We see that the second constructor also includes a Referencequeue object, and many of our subsequent operations need to be done with this object.
After the GC reclaims the object referred to by the reference (which actually refers to the object that the referent points to, the other phantomreference is before the recycle, finalize), the reference is added to the referencequeue to which it is bound. The program perceives reference events that are collected by GC by calling the Referencequeue Remove method or the poll method. Here is a section of reference source code:

Static private class Lock {};

private static lock lock = new Lock ();  /* List of References waiting to be enqueued.  The collector adds * References to this list while the Reference-handler thread removes * them.
This list was protected by the above lock object.

 * private static Reference pending = NULL; /* high-priority thread to Enqueue pending References * * private static class Referencehandler extends thread {R
     Eferencehandler (Threadgroup G, String name) {Super (G, name); public void Run () {for (;;)
             {Reference R;
                     Synchronized (lock) {if (pending!= null) {r = pending;
                     Reference rn = R.next; Pending = (Rn = r)?
                     Null:rn;
                 R.next = R;
                     else {try {lock.wait (); catch (Interruptedexception x) {} contiNue }//Fast path for cleaners if (r instanceof Cleaner) {(Clean
                 ER). Clean ();
             Continue
             } referencequeue q = r.queue;
         if (q!= referencequeue.null) Q.enqueue (R);
     }} static {Threadgroup TG = Thread.CurrentThread (). Getthreadgroup ();
          for (Threadgroup TGN = TG;
          TGN!= null;
     TG = tgn, TGN = Tg.getparent ());
     Thread handler = new Referencehandler (TG, "Reference handler"); /* If There were a special system-only priority greater than * max_priority, it would is used here * *
     Dler.setpriority (thread.max_priority);
     Handler.setdaemon (TRUE);
 Handler.start (); }

Referencehandler This thread starts as a daemon when the reference class initializes. Note that there is a reference type of member variable Pending,referencehandler loops to detect if the pending is empty and suspends waiting if it is empty. When a reference object is reclaimed at the GC stage, it is added to the pending, then wakes up Referencehandler and joins reference in Referencequeue. Now you can use Referencequeue to do some follow-up operation, take the classic Weakhashmap to say, first look at its entry:

Private final referencequeue<object> queue = new referencequeue<> ();

/**
 * The entries in this hash table extend WeakReference, using its main ref
 * field as the key.
 * *
private static class Entry<k,v> extends Weakreference<object> implements map.entry<k,v> {
    V value;
    int hash;
    Entry<k,v> Next;

    Entry (Object key, V value,
          referencequeue<object> queue,
          int hash, entry<k,v> next) {
        super ( Key, queue);  Initialize referent
        this.value = value with key;
        This.hash  = hash;
        This.next  = next;
    Omitted
}

The

entry inherits WeakReference, so it has the nature of a weak reference. This lets the weak reference point to the object that the key value refers to, so that when no more strong references point to the object that the key refers to, the target object is dropped by GC and the entry holding the key is added to the referencequeue that the queue refers to. Since the key value is no, the nature of this entry is not the meaning of existence, so have to find a chance to cut it off. Weakhashmap this point to the time when you call the GetTable or size method, you first perform a cleanup, which relies on reference objects that refer to records in queue queues.

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.