📄 runtime.java
字号:
/* Runtime.java -- access to the VM process Copyright (C) 1998, 2002, 2003, 2004, 2005, 2006 Free Software FoundationThis file is part of GNU Classpath.GNU Classpath is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2, or (at your option)any later version.GNU Classpath is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNUGeneral Public License for more details.You should have received a copy of the GNU General Public Licensealong with GNU Classpath; see the file COPYING. If not, write to theFree Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA02110-1301 USA.Linking this library statically or dynamically with other modules ismaking a combined work based on this library. Thus, the terms andconditions of the GNU General Public License cover the wholecombination.As a special exception, the copyright holders of this library give youpermission to link this library with independent modules to produce anexecutable, regardless of the license terms of these independentmodules, and to copy and distribute the resulting executable underterms of your choice, provided that you also meet, for each linkedindependent module, the terms and conditions of the license of thatmodule. An independent module is a module which is not derived fromor based on this library. If you modify this library, you may extendthis exception to your version of the library, but you are notobligated to do so. If you do not wish to do so, delete thisexception statement from your version. */package java.lang;import gnu.classpath.SystemProperties;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.HashSet;import java.util.Iterator;import java.util.Set;import java.util.StringTokenizer;/** * Runtime represents the Virtual Machine. * * @author John Keiser * @author Eric Blake (ebb9@email.byu.edu) * @author Jeroen Frijters */// No idea why this class isn't final, since you can't build a subclass!public class Runtime{ /** * The library path, to search when loading libraries. We can also safely use * this as a lock for synchronization. */ private final String[] libpath; static { init(); } /** * The thread that started the exit sequence. Access to this field must * be thread-safe; lock on libpath to avoid deadlock with user code. * <code>runFinalization()</code> may want to look at this to see if ALL * finalizers should be run, because the virtual machine is about to halt. */ private Thread exitSequence; /** * All shutdown hooks. This is initialized lazily, and set to null once all * shutdown hooks have run. Access to this field must be thread-safe; lock * on libpath to avoid deadlock with user code. */ private Set shutdownHooks; /** True if we should finalize on exit. */ private boolean finalizeOnExit; /** * The one and only runtime instance. */ private static final Runtime current = new Runtime(); /** * Not instantiable by a user, this should only create one instance. */ private Runtime() { if (current != null) throw new InternalError("Attempt to recreate Runtime"); // We don't use libpath in the libgcj implementation. We still // set it to something to allow the various synchronizations to // work. libpath = new String[0]; } /** * Get the current Runtime object for this JVM. This is necessary to access * the many instance methods of this class. * * @return the current Runtime object */ public static Runtime getRuntime() { return current; } /** * Exit the Java runtime. This method will either throw a SecurityException * or it will never return. The status code is returned to the system; often * a non-zero status code indicates an abnormal exit. Of course, there is a * security check, <code>checkExit(status)</code>. * * <p>First, all shutdown hooks are run, in unspecified order, and * concurrently. Next, if finalization on exit has been enabled, all pending * finalizers are run. Finally, the system calls <code>halt</code>.</p> * * <p>If this is run a second time after shutdown has already started, there * are two actions. If shutdown hooks are still executing, it blocks * indefinitely. Otherwise, if the status is nonzero it halts immediately; * if it is zero, it blocks indefinitely. This is typically called by * <code>System.exit</code>.</p> * * @param status the status to exit with * @throws SecurityException if permission is denied * @see #addShutdownHook(Thread) * @see #runFinalizersOnExit(boolean) * @see #runFinalization() * @see #halt(int) */ public void exit(int status) { SecurityManager sm = SecurityManager.current; // Be thread-safe! if (sm != null) sm.checkExit(status); if (runShutdownHooks()) halt(status); // Someone else already called runShutdownHooks(). // Make sure we are not/no longer in the shutdownHooks set. // And wait till the thread that is calling runShutdownHooks() finishes. synchronized (libpath) { if (shutdownHooks != null) { shutdownHooks.remove(Thread.currentThread()); // Interrupt the exit sequence thread, in case it was waiting // inside a join on our thread. exitSequence.interrupt(); // Shutdown hooks are still running, so we clear status to // make sure we don't halt. status = 0; } } // If exit() is called again after the shutdown hooks have run, but // while finalization for exit is going on and the status is non-zero // we halt immediately. if (status != 0) halt(status); while (true) try { exitSequence.join(); } catch (InterruptedException e) { // Ignore, we've suspended indefinitely to let all shutdown // hooks complete, and to let any non-zero exits through, because // this is a duplicate call to exit(0). } } /** * On first invocation, run all the shutdown hooks and return true. * Any subsequent invocations will simply return false. * Note that it is package accessible so that VMRuntime can call it * when VM exit is not triggered by a call to Runtime.exit(). * * @return was the current thread the first one to call this method? */ boolean runShutdownHooks() { boolean first = false; synchronized (libpath) // Synch on libpath, not this, to avoid deadlock. { if (exitSequence == null) { first = true; exitSequence = Thread.currentThread(); if (shutdownHooks != null) { Iterator i = shutdownHooks.iterator(); while (i.hasNext()) // Start all shutdown hooks. try { ((Thread) i.next()).start(); } catch (IllegalThreadStateException e) { i.remove(); } } } } if (first) { if (shutdownHooks != null) { // Check progress of all shutdown hooks. As a hook completes, // remove it from the set. If a hook calls exit, it removes // itself from the set, then waits indefinitely on the // exitSequence thread. Once the set is empty, set it to null to // signal all finalizer threads that halt may be called. while (true) { Thread[] hooks; synchronized (libpath) { hooks = new Thread[shutdownHooks.size()]; shutdownHooks.toArray(hooks); } if (hooks.length == 0) break; for (int i = 0; i < hooks.length; i++) { try { synchronized (libpath) { if (!shutdownHooks.contains(hooks[i])) continue; } hooks[i].join(); synchronized (libpath) { shutdownHooks.remove(hooks[i]); } } catch (InterruptedException x) { // continue waiting on the next thread } } } synchronized (libpath) { shutdownHooks = null; } } // Run finalization on all finalizable objects (even if they are // still reachable). runFinalizationForExit(); } return first; } /** * Register a new shutdown hook. This is invoked when the program exits * normally (because all non-daemon threads ended, or because * <code>System.exit</code> was invoked), or when the user terminates * the virtual machine (such as by typing ^C, or logging off). There is * a security check to add hooks, * <code>RuntimePermission("shutdownHooks")</code>. * * <p>The hook must be an initialized, but unstarted Thread. The threads * are run concurrently, and started in an arbitrary order; and user * threads or daemons may still be running. Once shutdown hooks have * started, they must all complete, or else you must use <code>halt</code>, * to actually finish the shutdown sequence. Attempts to modify hooks * after shutdown has started result in IllegalStateExceptions.</p> * * <p>It is imperative that you code shutdown hooks defensively, as you * do not want to deadlock, and have no idea what other hooks will be * running concurrently. It is also a good idea to finish quickly, as the * virtual machine really wants to shut down!</p> * * <p>There are no guarantees that such hooks will run, as there are ways * to forcibly kill a process. But in such a drastic case, shutdown hooks * would do little for you in the first place.</p> * * @param hook an initialized, unstarted Thread * @throws IllegalArgumentException if the hook is already registered or run * @throws IllegalStateException if the virtual machine is already in * the shutdown sequence * @throws SecurityException if permission is denied * @since 1.3 * @see #removeShutdownHook(Thread) * @see #exit(int) * @see #halt(int) */ public void addShutdownHook(Thread hook) { SecurityManager sm = SecurityManager.current; // Be thread-safe! if (sm != null) sm.checkPermission(new RuntimePermission("shutdownHooks")); if (hook.isAlive() || hook.getThreadGroup() == null) throw new IllegalArgumentException("The hook thread " + hook + " must not have been already run or started"); synchronized (libpath) { if (exitSequence != null) throw new IllegalStateException("The Virtual Machine is exiting. It is not possible anymore to add any hooks"); if (shutdownHooks == null) shutdownHooks = new HashSet(); // Lazy initialization. if (! shutdownHooks.add(hook)) throw new IllegalArgumentException(hook.toString() + " had already been inserted"); } } /** * De-register a shutdown hook. As when you registered it, there is a * security check to remove hooks, * <code>RuntimePermission("shutdownHooks")</code>. * * @param hook the hook to remove * @return true if the hook was successfully removed, false if it was not * registered in the first place * @throws IllegalStateException if the virtual machine is already in * the shutdown sequence * @throws SecurityException if permission is denied * @since 1.3 * @see #addShutdownHook(Thread) * @see #exit(int) * @see #halt(int) */ public boolean removeShutdownHook(Thread hook) { SecurityManager sm = SecurityManager.current; // Be thread-safe! if (sm != null) sm.checkPermission(new RuntimePermission("shutdownHooks")); synchronized (libpath) { if (exitSequence != null) throw new IllegalStateException(); if (shutdownHooks != null) return shutdownHooks.remove(hook); } return false; } /** * Forcibly terminate the virtual machine. This call never returns. It is * much more severe than <code>exit</code>, as it bypasses all shutdown * hooks and initializers. Use caution in calling this! Of course, there is * a security check, <code>checkExit(status)</code>. * * @param status the status to exit with * @throws SecurityException if permission is denied * @since 1.3 * @see #exit(int) * @see #addShutdownHook(Thread) */ public void halt(int status) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -