Finalizer.java 8.0 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29
 */

package java.lang.ref;

import java.security.PrivilegedAction;
import java.security.AccessController;
30 31 32
import sun.misc.JavaLangAccess;
import sun.misc.SharedSecrets;
import sun.misc.VM;
D
duke 已提交
33

34 35 36
final class Finalizer extends FinalReference<Object> { /* Package-private; must be in
                                                          same package as the Reference
                                                          class */
D
duke 已提交
37

38
    private static ReferenceQueue<Object> queue = new ReferenceQueue<>();
39 40
    private static Finalizer unfinalized = null;
    private static final Object lock = new Object();
D
duke 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

    private Finalizer
        next = null,
        prev = null;

    private boolean hasBeenFinalized() {
        return (next == this);
    }

    private void add() {
        synchronized (lock) {
            if (unfinalized != null) {
                this.next = unfinalized;
                unfinalized.prev = this;
            }
            unfinalized = this;
        }
    }

    private void remove() {
        synchronized (lock) {
            if (unfinalized == this) {
                if (this.next != null) {
                    unfinalized = this.next;
                } else {
                    unfinalized = this.prev;
                }
            }
            if (this.next != null) {
                this.next.prev = this.prev;
            }
            if (this.prev != null) {
                this.prev.next = this.next;
            }
            this.next = this;   /* Indicates that this has been finalized */
            this.prev = this;
        }
    }

    private Finalizer(Object finalizee) {
        super(finalizee, queue);
        add();
    }

85 86 87 88
    static ReferenceQueue<Object> getQueue() {
        return queue;
    }

D
duke 已提交
89 90 91 92 93
    /* Invoked by VM */
    static void register(Object finalizee) {
        new Finalizer(finalizee);
    }

94
    private void runFinalizer(JavaLangAccess jla) {
D
duke 已提交
95 96 97 98 99 100 101
        synchronized (this) {
            if (hasBeenFinalized()) return;
            remove();
        }
        try {
            Object finalizee = this.get();
            if (finalizee != null && !(finalizee instanceof java.lang.Enum)) {
102 103
                jla.invokeFinalize(finalizee);

D
duke 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
                /* Clear stack slot containing this variable, to decrease
                   the chances of false retention with a conservative GC */
                finalizee = null;
            }
        } catch (Throwable x) { }
        super.clear();
    }

    /* Create a privileged secondary finalizer thread in the system thread
       group for the given Runnable, and wait for it to complete.

       This method is used by both runFinalization and runFinalizersOnExit.
       The former method invokes all pending finalizers, while the latter
       invokes all uninvoked finalizers if on-exit finalization has been
       enabled.

       These two methods could have been implemented by offloading their work
       to the regular finalizer thread and waiting for that thread to finish.
       The advantage of creating a fresh thread, however, is that it insulates
       invokers of these methods from a stalled or deadlocked finalizer thread.
     */
    private static void forkSecondaryFinalizer(final Runnable proc) {
126 127 128
        AccessController.doPrivileged(
            new PrivilegedAction<Void>() {
                public Void run() {
129 130 131 132 133 134 135 136 137 138 139 140
                    ThreadGroup tg = Thread.currentThread().getThreadGroup();
                    for (ThreadGroup tgn = tg;
                         tgn != null;
                         tg = tgn, tgn = tg.getParent());
                    Thread sft = new Thread(tg, proc, "Secondary finalizer");
                    sft.start();
                    try {
                        sft.join();
                    } catch (InterruptedException x) {
                        Thread.currentThread().interrupt();
                    }
                    return null;
141
                }});
D
duke 已提交
142 143 144 145
    }

    /* Called by Runtime.runFinalization() */
    static void runFinalization() {
146 147 148 149
        if (!VM.isBooted()) {
            return;
        }

D
duke 已提交
150
        forkSecondaryFinalizer(new Runnable() {
151
            private volatile boolean running;
D
duke 已提交
152
            public void run() {
153
                // in case of recursive call to run()
154 155
                if (running)
                    return;
156
                final JavaLangAccess jla = SharedSecrets.getJavaLangAccess();
157
                running = true;
D
duke 已提交
158 159 160
                for (;;) {
                    Finalizer f = (Finalizer)queue.poll();
                    if (f == null) break;
161
                    f.runFinalizer(jla);
D
duke 已提交
162 163 164 165 166 167 168
                }
            }
        });
    }

    /* Invoked by java.lang.Shutdown */
    static void runAllFinalizers() {
169 170 171 172
        if (!VM.isBooted()) {
            return;
        }

D
duke 已提交
173
        forkSecondaryFinalizer(new Runnable() {
174
            private volatile boolean running;
D
duke 已提交
175
            public void run() {
176
                // in case of recursive call to run()
177 178
                if (running)
                    return;
179
                final JavaLangAccess jla = SharedSecrets.getJavaLangAccess();
180
                running = true;
D
duke 已提交
181 182 183 184 185 186 187
                for (;;) {
                    Finalizer f;
                    synchronized (lock) {
                        f = unfinalized;
                        if (f == null) break;
                        unfinalized = f.next;
                    }
188
                    f.runFinalizer(jla);
D
duke 已提交
189 190 191 192
                }}});
    }

    private static class FinalizerThread extends Thread {
193
        private volatile boolean running;
D
duke 已提交
194 195 196 197
        FinalizerThread(ThreadGroup g) {
            super(g, "Finalizer");
        }
        public void run() {
198
            // in case of recursive call to run()
199 200
            if (running)
                return;
201 202 203 204 205 206 207 208 209 210 211 212

            // 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();
213
            running = true;
D
duke 已提交
214 215 216
            for (;;) {
                try {
                    Finalizer f = (Finalizer)queue.remove();
217
                    f.runFinalizer(jla);
D
duke 已提交
218
                } catch (InterruptedException x) {
219
                    // ignore and continue
D
duke 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
                }
            }
        }
    }

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

}