Shutdown.java revision 1ae149ae8db46adac5723c739d53dd82a1cf2e1a
1/*
2 * Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.lang;
27
28
29/**
30 * Package-private utility class containing data structures and logic
31 * governing the virtual-machine shutdown sequence.
32 *
33 * @author   Mark Reinhold
34 * @since    1.3
35 *
36 * @hide
37 */
38// Android-changed: Make class public.
39public class Shutdown {
40
41    /* Shutdown state */
42    private static final int RUNNING = 0;
43    private static final int HOOKS = 1;
44    private static final int FINALIZERS = 2;
45    private static int state = RUNNING;
46
47    /* Should we run all finalizers upon exit? */
48    private static boolean runFinalizersOnExit = false;
49
50    // The system shutdown hooks are registered with a predefined slot.
51    // The list of shutdown hooks is as follows:
52    // (0) Console restore hook
53    // (1) Application hooks
54    // (2) DeleteOnExit hook
55    private static final int MAX_SYSTEM_HOOKS = 10;
56    private static final Runnable[] hooks = new Runnable[MAX_SYSTEM_HOOKS];
57
58    // the index of the currently running shutdown hook to the hooks array
59    private static int currentRunningHook = 0;
60
61    /* The preceding static fields are protected by this lock */
62    private static class Lock { };
63    private static Object lock = new Lock();
64
65    /* Lock object for the native halt method */
66    private static Object haltLock = new Lock();
67
68    /* Invoked by Runtime.runFinalizersOnExit */
69    static void setRunFinalizersOnExit(boolean run) {
70        synchronized (lock) {
71            runFinalizersOnExit = run;
72        }
73    }
74
75
76    /**
77     * Add a new shutdown hook.  Checks the shutdown state and the hook itself,
78     * but does not do any security checks.
79     *
80     * The registerShutdownInProgress parameter should be false except
81     * registering the DeleteOnExitHook since the first file may
82     * be added to the delete on exit list by the application shutdown
83     * hooks.
84     *
85     * @params slot  the slot in the shutdown hook array, whose element
86     *               will be invoked in order during shutdown
87     * @params registerShutdownInProgress true to allow the hook
88     *               to be registered even if the shutdown is in progress.
89     * @params hook  the hook to be registered
90     *
91     * @throw IllegalStateException
92     *        if registerShutdownInProgress is false and shutdown is in progress; or
93     *        if registerShutdownInProgress is true and the shutdown process
94     *           already passes the given slot
95     *
96     * @hide
97     */
98    // Android-changed: make public.
99    public static void add(int slot, boolean registerShutdownInProgress, Runnable hook) {
100        synchronized (lock) {
101            if (hooks[slot] != null)
102                throw new InternalError("Shutdown hook at slot " + slot + " already registered");
103
104            if (!registerShutdownInProgress) {
105                if (state > RUNNING)
106                    throw new IllegalStateException("Shutdown in progress");
107            } else {
108                if (state > HOOKS || (state == HOOKS && slot <= currentRunningHook))
109                    throw new IllegalStateException("Shutdown in progress");
110            }
111
112            hooks[slot] = hook;
113        }
114    }
115
116    /* Run all registered shutdown hooks
117     */
118    private static void runHooks() {
119        for (int i=0; i < MAX_SYSTEM_HOOKS; i++) {
120            try {
121                Runnable hook;
122                synchronized (lock) {
123                    // acquire the lock to make sure the hook registered during
124                    // shutdown is visible here.
125                    currentRunningHook = i;
126                    hook = hooks[i];
127                }
128                if (hook != null) hook.run();
129            } catch(Throwable t) {
130                if (t instanceof ThreadDeath) {
131                    ThreadDeath td = (ThreadDeath)t;
132                    throw td;
133                }
134            }
135        }
136    }
137
138    /* The halt method is synchronized on the halt lock
139     * to avoid corruption of the delete-on-shutdown file list.
140     * It invokes the true native halt method.
141     */
142    static void halt(int status) {
143        synchronized (haltLock) {
144            halt0(status);
145        }
146    }
147
148    static native void halt0(int status);
149
150    /* Wormhole for invoking java.lang.ref.Finalizer.runAllFinalizers */
151    private static native void runAllFinalizers();
152
153
154    /* The actual shutdown sequence is defined here.
155     *
156     * If it weren't for runFinalizersOnExit, this would be simple -- we'd just
157     * run the hooks and then halt.  Instead we need to keep track of whether
158     * we're running hooks or finalizers.  In the latter case a finalizer could
159     * invoke exit(1) to cause immediate termination, while in the former case
160     * any further invocations of exit(n), for any n, simply stall.  Note that
161     * if on-exit finalizers are enabled they're run iff the shutdown is
162     * initiated by an exit(0); they're never run on exit(n) for n != 0 or in
163     * response to SIGINT, SIGTERM, etc.
164     */
165    private static void sequence() {
166        synchronized (lock) {
167            /* Guard against the possibility of a daemon thread invoking exit
168             * after DestroyJavaVM initiates the shutdown sequence
169             */
170            if (state != HOOKS) return;
171        }
172        runHooks();
173        boolean rfoe;
174        synchronized (lock) {
175            state = FINALIZERS;
176            rfoe = runFinalizersOnExit;
177        }
178        if (rfoe) runAllFinalizers();
179    }
180
181
182    /* Invoked by Runtime.exit, which does all the security checks.
183     * Also invoked by handlers for system-provided termination events,
184     * which should pass a nonzero status code.
185     */
186    static void exit(int status) {
187        boolean runMoreFinalizers = false;
188        synchronized (lock) {
189            if (status != 0) runFinalizersOnExit = false;
190            switch (state) {
191            case RUNNING:       /* Initiate shutdown */
192                state = HOOKS;
193                break;
194            case HOOKS:         /* Stall and halt */
195                break;
196            case FINALIZERS:
197                if (status != 0) {
198                    /* Halt immediately on nonzero status */
199                    halt(status);
200                } else {
201                    /* Compatibility with old behavior:
202                     * Run more finalizers and then halt
203                     */
204                    runMoreFinalizers = runFinalizersOnExit;
205                }
206                break;
207            }
208        }
209        if (runMoreFinalizers) {
210            runAllFinalizers();
211            halt(status);
212        }
213        synchronized (Shutdown.class) {
214            /* Synchronize on the class object, causing any other thread
215             * that attempts to initiate shutdown to stall indefinitely
216             */
217            sequence();
218            halt(status);
219        }
220    }
221
222
223    /* Invoked by the JNI DestroyJavaVM procedure when the last non-daemon
224     * thread has finished.  Unlike the exit method, this method does not
225     * actually halt the VM.
226     */
227    static void shutdown() {
228        synchronized (lock) {
229            switch (state) {
230            case RUNNING:       /* Initiate shutdown */
231                state = HOOKS;
232                break;
233            case HOOKS:         /* Stall and then return */
234            case FINALIZERS:
235                break;
236            }
237        }
238        synchronized (Shutdown.class) {
239            sequence();
240        }
241    }
242
243}
244