2011-11-18 78 views
3

我們知道,螺紋ReferenceHandler負責排隊參考實例未決的ReferenceQueue,看到這個代碼參考$ ReferenceHandler.run():通知ReferenceHandler線程時?

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

如果等待隊列爲空,那麼這個線程等待鎖定;

我的問題是何時該線程被通知?當掛起的實例被修改?

回答

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醒來。