欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Reference 博客分类: java.lang.ref Reference

程序员文章站 2024-02-05 18:03:16
...
Reference


一、总结

1.jdk 1.8.0

2.引用级别
  • FinalReference,不对外提供使用,类的访问权限为默认 protect,即使抛出 out of memory 异常也不会回收所占内存
  • SoftReference,在内存不够用时,在抛出 out of memory 前回收内存空间
  • WeakReference,第一次GC不回收,当第二次GC时回收,有限期到第二次GC前都在内存中
  • PhantomReference


3.引用对比
- 强引用 软引用 弱引用 虚引用
定义 强引用指的是,程序中有直接可达的引用,而不需要通过任何引用对象,如Object obj = new Object();中,obj为强引用 软引用,非强引用,但是可以通过软引用对象来访问。软引用的对象,只有在内存不足的时候(抛出OOM异常前),垃圾收集器会决定回收该软引用所指向的对象。软引用通常用于实现内存敏感的缓存。 弱引用,非强引用和软引用,但是可以通过弱引用对象来访问。弱引用的对象,不管内存是否足够,只要被垃圾收集器发现,该引用的对象就会被回收。实际的应用见WeakHashMap 虚引用,该引用必须和引用队列(ReferenceQueue)一起使用,一般用于实现追踪垃圾收集器的回收动作,比如在对象被回收的时候,会调用该对象的finalize方法,在使用虚引用可以实现该动作,也更加安全


4.其他
  • 子类不可直接继承;处于安全考虑,Reference 类与GC交互;实现方式:构造方法的访问权限为默认,即包外的类不可见
  • 对象封装了其它对象的引用,可以和普通的对象一样操作,在一定的限制条件下,支持和垃圾收集器的交互。即可以使用Reference对象来引用其它对象,但是最后还是会被垃圾收集器回收。程序有时候也需要在对象回收后被通知,以告知对象的可达性发生变更


5.流程

Reference
            
    
    博客分类: java.lang.ref Reference


二、源码分析


/**
 * 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> {


类的注释:
  • Reference 类是引用对象的抽象基类
  • Reference 类中定义了引用对象的常用操作
  • 由于引用对象是通过与垃圾回收器密切合作来实现的,因此,不能直接为此类创建子类


Reference 类不能被包外的类继承的实现:
  • Reference 类的构造方法的访问权限为默认,即同包内的类可见
  • 子类的构造方法默认通过  super() 调用父类的构造方法,访问不到父类的构造方法

    // 构造方法,两个
    // 区别:是否带有 ReferenceQueue 参数
    // 不带有  ReferenceQueue 参数的构造方法,当 Reference 被 GC 回收后直接由 Active 状态变为 InActive 状态
    
    Reference(T referent) {
        this(referent, null);
    }

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

    // 带有 ReferenceQueue 参数的构造方法,当 Reference 被 GC 回收后会被加入到 GC 自动加入到 pending-Reference list 中,即类中的属性 pengding  
    private static Reference<Object> pending = null;

    // 对应构造方法传入的两个参数
    private T referent;         /* Treated specially by GC */
    volatile ReferenceQueue<? super T> queue;



    // 不同状态队列的next元素
    /* When active:   NULL
     *     pending:   this
     *    Enqueued:   next reference in queue (or this if last)
     *    Inactive:   this
     */
    @SuppressWarnings("rawtypes")
    Reference next;


  • 使用:访问权限为默认,当前类中未使用到该属性;为同包中其他类中调用使用,如:ReferenceQueue 中使用到了
  • 作用:Reference 数据结构为链表,用于连接后续的对象
  • Reference next , 在  ReferenceQueue  中指代构造方法传入的参数中的  ReferenceQueue


Reference状态 ReferenceQueue中的next的指向
Active NULL
Pending 本身
Enqueued 下一个元素或本身(尾部的元素指向本身)
Inactive NULL


 /* 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.
     *
     *     Pending: An element of the pending-Reference list, waiting to be
     *     enqueued by the Reference-handler thread.  Unregistered instances
     *     are never in this state.
     *
     *     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.
     *
     *     Inactive: Nothing more to do.  Once an instance becomes Inactive its
     *     state will never change again.
     *
     * 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.
     *
     *     Pending: queue = ReferenceQueue with which instance is registered;
     *     next = this
     *
     *     Enqueued: queue = ReferenceQueue.ENQUEUED; next = Following instance
     *     in queue, or this if at end of list.
     *
     *     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.
     *
     * 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.
     */
    // 用于保存对象的引用,GC会根据不同Reference来特别对待,构造方法的参数
    private T referent;         /* Treated specially by GC */
    
    // 简述:如果需要通知机制,则保存的对对应的队列
    // 使用:构造方法的参数
    // 作用:创建Reference时,将Queue注册到Reference中,当该Reference所引用的对象
    // 被垃圾收集器回收时,会将该Reference放到该队列中,相当于一种通知机制
    volatile ReferenceQueue<? super T> queue;

    /* 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
     */
    // 指向队列中的下一个对象;不同于next,为当前类中使用
    transient private Reference<T> discovered;  /* used by VM */

    /* 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();

    /* 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.
     */
    // 等待进行 enqueued 操作的对象集合;
    // 当 Reference-handler 线程删除元素后,GC 将删除的元素加入此队列中;
    // 此集合通过上述的 lock 锁实现线程安全
    // 此集合通过 discovered 属性链接本身的元素
    // pending队列中的元素由GC自动加入(对象回收后放入此队列中)
    private static Reference<Object> pending = null;


由类中的属性得知:内部的数据结果是单链表

ReferenceQueue<? super T> queue 的作用
  • queue 通过构造方法传入,若无默认为 null,用于存入注册到队列上的引用对象
  • queue 区分不同状态的  Reference ,不同的状态对应不同的queue



Reference有4种状态
  • Active:Active状态的Reference会受到GC的特别关注,当GC察觉到引用的可达性变化为其它的状态之后,它的状态将变化为Pending或Inactive,到底转化为Pending状态还是Inactive状态取决于此Reference对象创建时是否注册了queue.如果注册了queue,则将添加此实例到pending-Reference list中。 新创建的Reference实例的状态是Active。
  • Pending:在pending-Reference list中等待着被Reference-handler 线程入队列queue中的元素就处于这个状态。没有注册queue的实例是永远不可能到达这一状态
  • Enqueued:队列中的对象的状态,当实例被移动到ReferenceQueue外时,Reference的状态为Inactive。没有注册ReferenceQueue的不可能到达这一状态的
  • Inactive:一旦一个实例变为Inactive,则这个状态永远都不会再被改变


Reference四种状态对应的队列
  • Active queue:刚创建的队列或队列中没有对象注入;next = null ;由构造方法可知,新创建的实例都处于此状态
  • Pending queue:
  • Enqueued queue:
  • Inactive queue:


    /* 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 {
            // 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);
            }
        }
    }





    /**
     * 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; // PhantomReference 的子类
        try {
            synchronized (lock) {
                // pengding Reference Queue 不为空
                if (pending != null) {
                    r = pending; // 将 pending 赋值给 r 
                    // 'instanceof' might throw OutOfMemoryError sometimes
                    // so do this before un-linking 'r' from the 'pending' chain...
                    // r 是否是 Cleaner 的实例对象
                    c = r instanceof Cleaner ? (Cleaner) r : null; 
                    // unlink 'r' from 'pending' chain
                    // pengding 指向下一个元素
                    pending = r.discovered;
                    r.discovered = null;
                } else {
                    // pending Reference Queue 为空
                    // The waiting on the lock may cause an OutOfMemoryError
                    // because it may try to allocate exception objects.
                    if (waitForNotify) {
                        lock.wait();
                    }
                    // retry if waited
                    return waitForNotify;
                }
            }
        } catch (OutOfMemoryError x) {
            // 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);
            }
        });
    }



从源码中可以看出,这个线程在Reference类的static构造块中启动,并且被设置为最高优先级和daemon状态。此线程要做的事情就是不断的的检查pending是否为null,如果pending不为null,则将pending进行enqueue,否则线程进行wait状态。

    /**
     * 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
     */
    // 返回当前引用对象的指向的对象;如果对象已经被清除或被GC回收,返回NULL
    public T get() {
        return this.referent;
    }

    /**
     * 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 -- */

    /**
     * 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);
    }

    /**
     * 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);
    }



博文参考:
《Java源码分析》:ReferenceQueue、Reference及其子类
Java Reference 源码分析
  • Reference
            
    
    博客分类: java.lang.ref Reference
  • 大小: 48.1 KB
相关标签: Reference