在前面的文章中对java 1.8中的Reference类做了详细的介绍。但是还有一个特殊的Reference并没有涉及,这就是FinalReference和其子类Finalizer。 其继承关系如下图:
FinalReference是Reference的子类,Finalizer继承了FinalReference。现在对其源码进行分析。
FinalReference的实现非常简单:
/**
* Final references, used to implement finalization
*/
class FinalReference<T> extends Reference<T> {
public FinalReference(T referent, ReferenceQueue<? super T> q) {
super(referent, q);
}
}
需要特别注意的是,这个类不是public的,其作用域在protected,也就是说除了java.lang.ref包中的类能访问之外,不能在任何自定义的代码中调用。这也说明这是一个jvm才能访问的类。该类只有一个子类,那就是Finalizer。 而且FilnalReference只实现了一个带队列的构造方法,必须使用ReferenceQueue。
Finalizer是finalReference的子类,对queue和lock进行了重写。Finalizer也是protected作用域,另外通过final修饰。不可被继承。
//final修饰的类不可被继承
final class Finalizer extends FinalReference<Object> { /* Package-private; must be in
same package as the Reference
class */
//重写了queue属性,Finalizer必须使用ReferenceQueue,因此一开始就对queue进行了实例化
private static ReferenceQueue<Object> queue = new ReferenceQueue<>();
private static Finalizer unfinalized = null;
//重载了锁
private static final Object lock = new Object();
//链表指针,Finalizer是个双向链表
private Finalizer
next = null,
prev = null;
//判断链表是否有下一个节点
private boolean hasBeenFinalized() {
return (next == this);
}
//链表中增加元素 注意此方法是private
private void add(){ ... }
//链表中删除元素 注意此方法是private
private void remove(){ ... }
//构造器 private
private Finalizer(Object finalizee) {
super(finalizee, queue);
add();
}
//register是非private的
/* Invoked by VM */
static void register(Object finalizee) {
new Finalizer(finalizee);
}
/* Called by Runtime.runFinalization() */
static void runFinalization() {
...
}
/* Invoked by java.lang.Shutdown */
static void runAllFinalizers(){
...
}
...
}
Finalizer的大部分方法都是private修饰,也就是说不能提供给外部调用,Finalizer没有public方法,构造器也是private修饰的。只提供3个非private的方法,register 、runFinalization 与runAllFinalizers。在一个对象中。 需要理解finalizer的调用时机,我们需要对Object中的finalize方法进行解读。 在object类中,有一个finalize方法及注释如下:
/**
* Called by the garbage collector on an object when garbage collection
* determines that there are no more references to the object.
* A subclass overrides the {@code finalize} method to dispose of
* system resources or to perform other cleanup.
* <p>
* The general contract of {@code finalize} is that it is invoked
* if and when the Java™ virtual
* machine has determined that there is no longer any
* means by which this object can be accessed by any thread that has
* not yet died, except as a result of an action taken by the
* finalization of some other object or class which is ready to be
* finalized. The {@code finalize} method may take any action, including
* making this object available again to other threads; the usual purpose
* of {@code finalize}, however, is to perform cleanup actions before
* the object is irrevocably discarded. For example, the finalize method
* for an object that represents an input/output connection might perform
* explicit I/O transactions to break the connection before the object is
* permanently discarded.
* <p>
* The {@code finalize} method of class {@code Object} performs no
* special action; it simply returns normally. Subclasses of
* {@code Object} may override this definition.
* <p>
* The Java programming language does not guarantee which thread will
* invoke the {@code finalize} method for any given object. It is
* guaranteed, however, that the thread that invokes finalize will not
* be holding any user-visible synchronization locks when finalize is
* invoked. If an uncaught exception is thrown by the finalize method,
* the exception is ignored and finalization of that object terminates.
* <p>
* After the {@code finalize} method has been invoked for an object, no
* further action is taken until the Java virtual machine has again
* determined that there is no longer any means by which this object can
* be accessed by any thread that has not yet died, including possible
* actions by other objects or classes which are ready to be finalized,
* at which point the object may be discarded.
* <p>
* The {@code finalize} method is never invoked more than once by a Java
* virtual machine for any given object.
* <p>
* Any exception thrown by the {@code finalize} method causes
* the finalization of this object to be halted, but is otherwise
* ignored.
*
* @throws Throwable the {@code Exception} raised by this method
* @see java.lang.ref.WeakReference
* @see java.lang.ref.PhantomReference
* @jls 12.6 Finalization of Class Instances
*/
protected void finalize() throws Throwable { }
其注释的大意为:
也就是说,finalize方法只会被jvm在GC的时候调用。具体何时调用,这是不确定的,jvm只能确保被调用这个方法之前对其他引用而言是不可达的,也就是说确认这个类已经将被gc回收。 因此,对于jvm而言,在这个类被创建的时候,jvm会遍历这个类的所有方法,包括父类的方法,只要有一个参数为空且返回void的非空finalize方法就认为这个类在创建对象的时候需要进行注册。之后就会调用register方法,将这个类以finalizer引用的形式进行注册。
jvm在注册的时候,实际上就是创建了一个Finalizer的链表。在GC的时候,如果发现对象只被Finalizer引用,则说明这个对象可以被回收了。那么就将其从引用对象链中取出,放入ReferenceQueue中。之后通知Finalizer Thread线程去消费。之后去调用finalize方法,可以查看这个FinalizerTHread的源码:
private static class FinalizerThread extends Thread {
private volatile boolean running;
FinalizerThread(ThreadGroup g) {
super(g, "Finalizer");
}
public void run() {
if (running)
return;
// Finalizer thread starts before System.initializeSystemClass
// is called. Wait until JavaLangAccess is available
while (!VM.isBooted()) {
// delay until VM completes initialization
try {
VM.awaitBooted();
} catch (InterruptedException x) {
// ignore and continue
}
}
final JavaLangAccess jla = SharedSecrets.getJavaLangAccess();
running = true;
for (;;) {
try {
Finalizer f = (Finalizer)queue.remove();
f.runFinalizer(jla);
} catch (InterruptedException x) {
// ignore and continue
}
}
}
}
jvm将重写了finalize方法的类注册到引用队列,Finalizer构成的链表中,在对象的引用状态变为Enqueued之后,jvm将这个对象添加到Pending-Reference的链表中,之后被ReferenceHandler处理,添加到ReferenceQueue中。而Finalizer Thread则不断的从ReferenceQueue中取出对象,执行finalize方法并回收。 这个Finalizer Thread请求的是runFinalizer方法。在runFinalizer方法中对finalize进行了invokeFinalize.
private void runFinalizer(JavaLangAccess jla) {
synchronized (this) {
if (hasBeenFinalized()) return;
remove();
}
try {
Object finalizee = this.get();
if (finalizee != null && !(finalizee instanceof java.lang.Enum)) {
jla.invokeFinalize(finalizee);
/* Clear stack slot containing this variable, to decrease
the chances of false retention with a conservative GC */
finalizee = null;
}
} catch (Throwable x) { }
super.clear();
}
线程的启动参数在静态代码块中:
static {
ThreadGroup tg = Thread.currentThread().getThreadGroup();
for (ThreadGroup tgn = tg;
tgn != null;
tg = tgn, tgn = tg.getParent());
Thread finalizer = new FinalizerThread(tg);
finalizer.setPriority(Thread.MAX_PRIORITY - 2);
finalizer.setDaemon(true);
finalizer.start();
}
可以看到这个线程是一个优先级比较低的守护线程。 Thread.MAX_PRIORITY - 2 。就意味着在CPU很紧张的情况下其被调度的优先级可能会受到影响,并不能立即执行。FinalizerThread业务很简单,从ReferenceQueue拿出Finalizer,执行finalize方法,并且忽略其抛出的所有异常。执行完毕后,该对象称为真正的垃圾对象,再次发生GC,这个对象就真正的被回收了。 Finalizer生命周期如下:
结合前文,不难发现Finalizer在GC过程中会存在如下结论:
对于Object中的finalize方法,需要注意的是: