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