Java8-Refernce<T>

以下为译文,代码注释的翻译。

Refernce主要是负责内存的一个状态,当然它还和java虚拟机,垃圾回收器打交道。Reference类首先把内存分为4种状态Active,Pending,Enqueued,Inactive。

Active,一般来说内存一开始被分配的状态都是 Active,
Pending 大概是指快要被放进队列的对象,也就是马上要回收的对象,
Enqueued 就是对象的内存已经被回收了,我们已经把这个对象放入到一个队列中,方便以后我们查询某个对象是否被回收,
Inactive就是最终的状态,不能再变为其它状态。
在JDK包中它有三个子类,SoftReference,WeakReference,PhantomReference。我们可以把一个对象包装成这三个子类来跟踪对象存活.

import java.lang.ref.ReferenceQueue;

import sun.misc.Cleaner;
import sun.misc.JavaLangRefAccess;
import sun.misc.SharedSecrets;

/**
 * Abstract base class for reference objects.  This class defines the
 * operations common to all reference objects.  Because reference objects are
 * implemented in close cooperation with the garbage collector, this class may
 * not be subclassed directly.
 * 
 * 引用对象的抽象积累,这个类定义了引用对象通用的操作。
 * 因为引用对象的实现和各个公司垃圾回收器的实现相关,所以这个类不能直接被子类化。
 *
 * @author   Mark Reinhold
 * @since    1.2
 */

public abstract class Reference<T> {

    /* A Reference instance is in one of four possible internal states:
     * 每一个引用实例都是以下四种内部状态之一
     *
     *     Active: Subject to special treatment by the garbage collector.  Some
     *     time after the collector detects that the reachability of the
     *     referent has changed to the appropriate state, it changes the
     *     instance's state to either Pending or Inactive, depending upon
     *     whether or not the instance was registered with a queue when it was
     *     created.  In the former case it also adds the instance to the
     *     pending-Reference list.  Newly-created instances are Active.
     *     
     *     Active:由垃圾回收器进行特殊处理。在垃圾回收器发现引用可达性状态发生改变以后,
     *     根据在创建实例时是否注册到队列,垃圾回收器改变实例的状态到Pending或者Inactive。
     *     改变实例状态到Pending的时候,实例同样会被添加到pending-Reference列表。
     *     任何新建的实例状态都是Active。
     *
     *     Pending: An element of the pending-Reference list, waiting to be
     *     enqueued by the Reference-handler thread.  Unregistered instances
     *     are never in this state.
     *     
     *     Pending:pending-Reference列表的元素,等待Reference-handler线程处理进行入队。
     *     未注册的实例永远不会有这个状态。
     *
     *     Enqueued: An element of the queue with which the instance was
     *     registered when it was created.  When an instance is removed from
     *     its ReferenceQueue, it is made Inactive.  Unregistered instances are
     *     never in this state.
     *     
     *     Enqueued:当实例创建时注册到队列,状态就是Enqueued。当实例从ReferenceQueue内移除时,
     *     它就变成了Inactive。未注册的对象没有这个状态。
     *
     *     Inactive: Nothing more to do.  Once an instance becomes Inactive its
     *     state will never change again.
     *     
     *     Inactive:不能再做任何事。一旦实例变成Inactive状态,它的状态将不再变更。
     *
     * The state is encoded in the queue and next fields as follows:
     * 
     * 各个状态的队列编码和下一个字段的编码根据以下规则:
     *
     *     Active: queue = ReferenceQueue with which instance is registered, or
     *     ReferenceQueue.NULL if it was not registered with a queue; next =
     *     null.
     *     
     *     Active:实例已经注册 queue = ReferenceQueue,实例未注册 queue = ReferenceQueue.NULL。
     *     next = null。
     *
     *     Pending: queue = ReferenceQueue with which instance is registered;
     *     next = this
     *     
     *     Pending:实例对象已经注册 queue = ReferenceQueue,next = this 
     *
     *     Enqueued: queue = ReferenceQueue.ENQUEUED; next = Following instance
     *     in queue, or this if at end of list.
     *     
     *     Enqueued:queue = ReferenceQueue.ENQUEUED;next = 队列内的下一个实例,当前实例是最后一个节点,next = this
     *
     *     Inactive: queue = ReferenceQueue.NULL; next = this.
     *     
     *     Inactive:queue = ReferenceQueue.NULL;next = this.
     *
     * With this scheme the collector need only examine the next field in order
     * to determine whether a Reference instance requires special treatment: If
     * the next field is null then the instance is active; if it is non-null,
     * then the collector should treat the instance normally.
     * 
     * 根据以上规则,垃圾回收器在处理引用实例只要判断 next是否是null即可。如果 next 是null,那么对象的状态是active。
     * 如果 next !=null,说明垃圾回收器应该正常处理实例。
     * 
     *
     * To ensure that a concurrent collector can discover active Reference
     * objects without interfering with application threads that may apply
     * the enqueue() method to those objects, collectors should link
     * discovered objects through the discovered field. The discovered
     * field is also used for linking Reference objects in the pending list.
     * 
     * 为了确保并发搜集器不用干预应用程序线程就能发现活跃的引用对象,它可以在这些对象上使用enqueue()方法,
     * 搜集器应该使用发现字段连接发现的对象。在pending list中,同样也使用发现字段连接引用对象。
     * 
     */

    /* GC特殊对待的引用 */
    private T referent;         /* Treated specially by GC */

    volatile ReferenceQueue<? super T> queue;

    /* When active:   NULL
     *     pending:   this
     *    Enqueued:   next reference in queue (or this if last)
     *    Inactive:   this
     */
    @SuppressWarnings("rawtypes")
    Reference next;

    /* When active:   next element in a discovered reference list maintained by GC (or this if last)
     *     pending:   next element in the pending list (or null if last)
     *   otherwise:   NULL
     */
    /*        active:  GC维护发现引用链的下一个元素(如果是最后一个元素,this)
     *        pending:  pending list中的小一个元素,如果是最后一个元素,null
     */
    transient private Reference<T> discovered;  /* used by VM */


    /*GC用于同步的对象。在每次搜集周期开始之前,GC必须先获得此锁。因此任何获得此锁的代码应该立即执行完毕,
     * 不能开辟新对象,避免调用用户代码。
     */
    /* Object used to synchronize with the garbage collector.  The collector
     * must acquire this lock at the beginning of each collection cycle.  It is
     * therefore critical that any code holding this lock complete as quickly
     * as possible, allocate no new objects, and avoid calling user code.
     */
    static private class Lock { }
    private static Lock lock = new Lock();

    /*等待进队的引用链。在Reference-handler线程移除它们的时候,搜集器把引用添加进它自己的链表。
     * 这个列表通过使用上面的lock对象来保护。列表使用发现字段来连接它的元素。
     */
    /* List of References waiting to be enqueued.  The collector adds
     * References to this list, while the Reference-handler thread removes
     * them.  This list is protected by the above lock object. The
     * list uses the discovered field to link its elements.
     */
    private static Reference<Object> pending = null;

    /*具有高优先级的线程,用于把带pending引用入队。
     */
    /* High-priority thread to enqueue pending References
     */
    private static class ReferenceHandler extends Thread {

        private static void ensureClassInitialized(Class<?> clazz) {
            try {
                Class.forName(clazz.getName(), true, clazz.getClassLoader());
            } catch (ClassNotFoundException e) {
                throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e);
            }
        }

        static {
            //加载并初始化InterruptedException.class 和 Cleaner.class,
            //这样在run方式的循环中就不用考虑内存不足导致类加载失败的问题.
            // pre-load and initialize InterruptedException and Cleaner classes
            // so that we don't get into trouble later in the run loop if there's
            // memory shortage while loading/initializing them lazily.
            ensureClassInitialized(InterruptedException.class);
            ensureClassInitialized(Cleaner.class);
        }

        ReferenceHandler(ThreadGroup g, String name) {
            super(g, name);
        }

        public void run() {
            while (true) {
                tryHandlePending(true);
            }
        }
    }

    /**
     * 如果存在pending引用,那么处理pending{@link Reference}引用。存在pending引用返回{@code true},
     * 如果不存在返回{@code false},那么程序可以去做一些其他有意义的事,而不是继续循环。
     * 
     * @param waitForNotify 如果true,并且当前不存在pending{@link Reference}引用,等待直到VM通知或者中断;
     *                         如果false,并且当前不存在pending{@link Reference}引用,立即返回
     * 
     * @return {@code true} 当前存在pending引用,并且已经被处理,或者收到来自VM的通知或线程被中断。要不然返回false
     */
    /**
     * Try handle pending {@link Reference} if there is one.<p>
     * Return {@code true} as a hint that there might be another
     * {@link Reference} pending or {@code false} when there are no more pending
     * {@link Reference}s at the moment and the program can do some other
     * useful work instead of looping.
     *
     * @param waitForNotify if {@code true} and there was no pending
     *                      {@link Reference}, wait until notified from VM
     *                      or interrupted; if {@code false}, return immediately
     *                      when there is no pending {@link Reference}.
     * @return {@code true} if there was a {@link Reference} pending and it
     *         was processed, or we waited for notification and either got it
     *         or thread was interrupted before being notified;
     *         {@code false} otherwise.
     */
    static boolean tryHandlePending(boolean waitForNotify) {
        Reference<Object> r;
        Cleaner c;
        try {
            synchronized (lock) {
                if (pending != null) {
                    r = pending;
                    //'instaanceof' 可能会抛出OutOfMemoryError
                    // 防止从pending链表上un-linking r后抛出异常,所以,先检测.
                    // 'instanceof' might throw OutOfMemoryError sometimes
                    // so do this before un-linking 'r' from the 'pending' chain...
                    c = r instanceof Cleaner ? (Cleaner) r : null;
                    //将r从pending 链上移除
                    // unlink 'r' from 'pending' chain
                    pending = r.discovered;
                    r.discovered = null;
                } else {
                    // lock 上的等待可能会抛出OutOfMemoryError,因为它可能去开辟一个exception对象.
                    // The waiting on the lock may cause an OutOfMemoryError
                    // because it may try to allocate exception objects.
                    if (waitForNotify) {
                        //waitForNotify 如果是true,等VM唤醒
                        lock.wait();
                    }
                    // retry if waited
                    return waitForNotify;
                }
            }
        } catch (OutOfMemoryError x) {
            //让出CPU时间片,这样可能会放弃一些存活的引用,这样GC就可以重新声明一些空间。
            //同样,也阻止上面 'r instanceof Cleaner'时 CPU密集循环,导致抛出许多OOME.
            // Give other threads CPU time so they hopefully drop some live references
            // and GC reclaims some space.
            // Also prevent CPU intensive spinning in case 'r instanceof Cleaner' above
            // persistently throws OOME for some time...
            Thread.yield();
            // retry
            //重试
            return true;
        } catch (InterruptedException x) {
            // retry
            //重试
            return true;
        }

        // Fast path for cleaners
        if (c != null) {
            c.clean();
            return true;
        }

        ReferenceQueue<? super Object> q = r.queue;
        if (q != ReferenceQueue.NULL) q.enqueue(r);
        return true;
    }

    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 be used here
         */
        handler.setPriority(Thread.MAX_PRIORITY);
        handler.setDaemon(true);
        handler.start();

        // provide access in SharedSecrets
        SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() {
            @Override
            public boolean tryHandlePendingReference() {
                return tryHandlePending(false);
            }
        });
    }

    /* -- Referent accessor and setters -- */

    /**
     * 返回当前引用的对象。 如果引用的对象已经被GC回收或者被程序回收,返回<code>null</code>
     */
    /**
     * Returns this reference object's referent.  If this reference object has
     * been cleared, either by the program or by the garbage collector, then
     * this method returns <code>null</code>.
     *
     * @return   The object to which this reference refers, or
     *           <code>null</code> if this reference object has been cleared
     */
    public T get() {
        return this.referent;
    }
    /**
     * 清理当前的引用对象,调用此方法不会导致对象入队。
     * <p> 这个方法仅被Java代码调用,当搜集器清理引用时,不会调用此方法。
     */
    /**
     * Clears this reference object.  Invoking this method will not cause this
     * object to be enqueued.
     *
     * <p> This method is invoked only by Java code; when the garbage collector
     * clears references it does so directly, without invoking this method.
     */
    public void clear() {
        this.referent = null;
    }


    /* -- Queue operations -- */
    /**
     * 当前引用的对象是否已经入队,可能是程序本身或者垃圾搜集器操作入队。
     * 如果在创建引用对象时未注册队列,那么返回<code>false</code>
     * 
     * @return <code>true</code> 引用对象已经入队
     */
    /**
     * Tells whether or not this reference object has been enqueued, either by
     * the program or by the garbage collector.  If this reference object was
     * not registered with a queue when it was created, then this method will
     * always return <code>false</code>.
     *
     * @return   <code>true</code> if and only if this reference object has
     *           been enqueued
     */
    public boolean isEnqueued() {
        return (this.queue == ReferenceQueue.ENQUEUED);
    }

    /**
     * 如果有注册,把当前引用对象入队.
     * 
     * <p> 这个方法仅被Java代码调用,当GC让引用对象入队时不调用此方法。
     * 
     * @return <code>true</code>如果当前引用对象入队成功,
     *            <code>false</code>如果已经入队或者在创建的时候未注册到队列.
     * 
     */
    /**
     * Adds this reference object to the queue with which it is registered,
     * if any.
     *
     * <p> This method is invoked only by Java code; when the garbage collector
     * enqueues references it does so directly, without invoking this method.
     *
     * @return   <code>true</code> if this reference object was successfully
     *           enqueued; <code>false</code> if it was already enqueued or if
     *           it was not registered with a queue when it was created
     */
    public boolean enqueue() {
        return this.queue.enqueue(this);
    }


    /* -- Constructors -- */

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

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

}

 插入一张偷来的图

原文地址:https://www.cnblogs.com/shuiyonglewodezzzzz/p/11121117.html