Java中的SoftReference,WeakReference和PhantomReference

SoftReference,WeakReference和PhantomReference都是继承自Reference抽象类,

在这个类中有一个static代码块,会给当前线程组和它的所有父亲都启动一个线程叫做ReferenceHandler,

ReferenceHandler会随时来检查是否有pending中是否有GC加入的已经清除的对象,然后将它们加入到Reference对于的ReferenceQueue中。

/* High-priority thread to enqueue pending References
 */
private static class ReferenceHandler extends Thread {

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

https://weblogs.java.net/blog/2006/05/04/understanding-weak-references

http://www.cnblogs.com/blogoflee/archive/2012/03/22/2411124.html