Reference类中有一个静态内部类:private static class ReferenceHandler extends Thread, 并且该ReferneceHandler在类初始化的时候就会作为一个daemon线程在后台运行,而且优先级最高:
12345678910111213
static{ThreadGrouptg=Thread.currentThread().getThreadGroup();for(ThreadGrouptgn=tg;tgn!=null;tg=tgn,tgn=tg.getParent());Threadhandler=newReferenceHandler(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();}
该ReferenceHandler的内部逻辑如下:
123456789101112131415161718192021222324252627
publicvoidrun(){for(;;){Referencer;synchronized(lock){if(pending!=null){r=pending;Referencern=r.next;pending=(rn==r)?null:rn;r.next=r;}else{try{lock.wait();}catch(InterruptedExceptionx){}continue;}}// Fast path for cleanersif(rinstanceofCleaner){((Cleaner)r).clean();continue;}ReferenceQueueq=r.queue;if(q!=ReferenceQueue.NULL)q.enqueue(r);}}