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

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


image.png

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356