Finalizer.java 7.9 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() {
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) {
                        Thread.currentThread().interrupt();
                    }
                    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
                // in case of recursive call to run()
150 151
                if (running)
                    return;
152
                final JavaLangAccess jla = SharedSecrets.getJavaLangAccess();
153
                running = true;
D
duke 已提交
154 155 156
                for (;;) {
                    Finalizer f = (Finalizer)queue.poll();
                    if (f == null) break;
157
                    f.runFinalizer(jla);
D
duke 已提交
158 159 160 161 162 163 164
                }
            }
        });
    }

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

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

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

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

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

}