什么时候通知ReferenceHandler线程?

时间:2011-11-18 11:02:18

标签: java reference jvm

我们知道,线程 ReferenceHandler 负责将待处理的Reference实例排入 ReferenceQueue ,请参阅Reference $ ReferenceHandler.run()中的以下代码:

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

如果挂起队列为空,则此线程正在等待锁定;

我的问题是什么时候通知这个帖子?修改待处理实例时?

1 个答案:

答案 0 :(得分:2)

来自代码

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

这意味着收集器在完成后将notify(),并需要唤醒ReferenceHandler。