Finalizer.java 7.7 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2013, 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 85 86 87 88 89

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

    /* Invoked by VM */
    static void register(Object finalizee) {
        new Finalizer(finalizee);
    }

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

D
duke 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
                /* 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) {
122 123 124
        AccessController.doPrivileged(
            new PrivilegedAction<Void>() {
                public Void run() {
D
duke 已提交
125 126 127 128 129 130 131 132 133 134 135 136
                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) {
                    /* Ignore */
                }
                return null;
137
                }});
D
duke 已提交
138 139 140 141
    }

    /* Called by Runtime.runFinalization() */
    static void runFinalization() {
142 143 144 145
        if (!VM.isBooted()) {
            return;
        }

D
duke 已提交
146
        forkSecondaryFinalizer(new Runnable() {
147
            private volatile boolean running;
D
duke 已提交
148
            public void run() {
149 150
                if (running)
                    return;
151
                final JavaLangAccess jla = SharedSecrets.getJavaLangAccess();
152
                running = true;
D
duke 已提交
153 154 155
                for (;;) {
                    Finalizer f = (Finalizer)queue.poll();
                    if (f == null) break;
156
                    f.runFinalizer(jla);
D
duke 已提交
157 158 159 160 161 162 163
                }
            }
        });
    }

    /* Invoked by java.lang.Shutdown */
    static void runAllFinalizers() {
164 165 166 167
        if (!VM.isBooted()) {
            return;
        }

D
duke 已提交
168
        forkSecondaryFinalizer(new Runnable() {
169
            private volatile boolean running;
D
duke 已提交
170
            public void run() {
171 172
                if (running)
                    return;
173
                final JavaLangAccess jla = SharedSecrets.getJavaLangAccess();
174
                running = true;
D
duke 已提交
175 176 177 178 179 180 181
                for (;;) {
                    Finalizer f;
                    synchronized (lock) {
                        f = unfinalized;
                        if (f == null) break;
                        unfinalized = f.next;
                    }
182
                    f.runFinalizer(jla);
D
duke 已提交
183 184 185 186
                }}});
    }

    private static class FinalizerThread extends Thread {
187
        private volatile boolean running;
D
duke 已提交
188 189 190 191
        FinalizerThread(ThreadGroup g) {
            super(g, "Finalizer");
        }
        public void run() {
192 193
            if (running)
                return;
194 195 196 197 198 199 200 201 202 203 204 205

            // 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();
206
            running = true;
D
duke 已提交
207 208 209
            for (;;) {
                try {
                    Finalizer f = (Finalizer)queue.remove();
210
                    f.runFinalizer(jla);
D
duke 已提交
211
                } catch (InterruptedException x) {
212
                    // ignore and continue
D
duke 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
                }
            }
        }
    }

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

}