java中的reference(三): FinalReference和Finalizer的源码分析

时间:2022-07-22
本文章向大家介绍java中的reference(三): FinalReference和Finalizer的源码分析,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

文章目录

在前面的文章中对java 1.8中的Reference类做了详细的介绍。但是还有一个特殊的Reference并没有涉及,这就是FinalReference和其子类Finalizer。 其继承关系如下图:

FinalReference是Reference的子类,Finalizer继承了FinalReference。现在对其源码进行分析。

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

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&trade; 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方法,那么GC在回收这个对象之前,会将finalize方法进行调用。finalize的一般约定是,jvm虚拟机已经确定没有任何引用或者线程访问此对象,就会调用这个finalize方法。在finalize方法中可以进行任何操作,包括该对象再次对其他线程进行调用。这个方法的目的是在gc回收对象之前,再次对之前未关闭的资源进行回收。如IO操作中的连接等。
  • java虚拟机并不保证哪个线程会具体调用finalize方法,但是可以保证调用finalize方法的时候不会有任何用户可见的同步锁。如果finalize方法中出现任何异常,则这些异常会被忽略,且finalize方法会终止。
  • 在一个对象调用finalize方法之后,在jvm确认这个对象没有任何其他对象能访问之前,也就是说jvm确认这个对象不是垃圾之前。finalize方法不会执行。
  • finalize 方法只会被虚拟机执行一次。
  • finalize方法中的异常会被忽略,之后finalize方法会终止。

也就是说,finalize方法只会被jvm在GC的时候调用。具体何时调用,这是不确定的,jvm只能确保被调用这个方法之前对其他引用而言是不可达的,也就是说确认这个类已经将被gc回收。 因此,对于jvm而言,在这个类被创建的时候,jvm会遍历这个类的所有方法,包括父类的方法,只要有一个参数为空且返回void的非空finalize方法就认为这个类在创建对象的时候需要进行注册。之后就会调用register方法,将这个类以finalizer引用的形式进行注册。

FinalizerThread线程

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生命周期如下:

  • 在创建对象的时候,如果重写了finalize方法,jvm就会同时创建一个Finalizer对象。
  • 所有的Finalizer对象构成一个双向链表
  • 所有的Finalizer对象都有一个名为queue的ReferenceQueue队列
  • GC在执行标记的最后阶段,会把Finalizer的对象加入到Reference的pending-list 链表中。
  • ReferenceHandler会将pending-list中的对象取出,放置到这个ReferenceQueue中。对于finalReference而言,这个queue即使初始化的时候创建的static的queue。对于所有的FinalReference全局只有一个ReferenceQueue。
  • Finalizer中有一个专门的守护线程 Finalizer Thread,这个线程中有一个死循环,专门从queue中取出对象,并执行Finalizer中引用对象的finalize方法。之后从队列中移除,强引用消除。
  • 再次GC 这个Finalizer的对象没有任何引用,因此可能被回收掉。

总结

结合前文,不难发现Finalizer在GC过程中会存在如下结论:

  • 对象如果有finalizer方法,那么就会被Finalizer临时强引用,而变成一强引用的话,是无法被立即回收的。
  • 如果有finalizer方法的话,只有在FinalizerThread 执行完成finalize()之后才有可能在下次GC中回收。由于Thread的优先级,可能会导致存在GC过多次之后还有一直未执行finalizer的对象。
  • 如果CPU竞争严重的话,FinalizerThread的线程优先级可能导致大部分对象未被执行finalizer而无法回收。导致大量的内存浪费。
  • 如果对象的finalizer方法一直不执行,可能会导致这些对象由于gc年龄而被分配到old区,如果这些对象越来越多,则有可能导致FullGC,GC时间过长甚至OOM。
  • 需要说明一个c++程序员的误区是,finalize方法被调用之后这个对象还是存在的,只是有可能在下次GC中被回收。

对于Object中的finalize方法,需要注意的是:

  • 如果非必要,尽量不要重写finalize方法
  • 如果有可能,尽量不要用finalize方法来关闭外部资源,使用try-finally来关闭可以做的更好、更及时。
  • 做为java程序员,最好是忘掉finalize方法的存在。实现机制需要详细掌握。这也是为什么要忘掉的原因。在各大厂面试中肯定会存在。

参考: JDK源码-FinalReference