svn merge -r108665:108708 svn+ssh://gcc.gnu.org/svn/gcc/trunk
[official-gcc.git] / libjava / java / lang / Runtime.java
bloba30a44b2c229b16ebe1585629ea70ad2274ea93a
1 /* Runtime.java -- access to the VM process
2 Copyright (C) 1998, 2002, 2003, 2004, 2005 Free Software Foundation
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 02110-1301 USA.
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
39 package java.lang;
41 import gnu.classpath.SystemProperties;
43 import java.io.File;
44 import java.io.IOException;
45 import java.io.InputStream;
46 import java.io.OutputStream;
47 import java.util.HashSet;
48 import java.util.Iterator;
49 import java.util.Set;
50 import java.util.StringTokenizer;
52 /**
53 * Runtime represents the Virtual Machine.
55 * @author John Keiser
56 * @author Eric Blake (ebb9@email.byu.edu)
57 * @author Jeroen Frijters
59 // No idea why this class isn't final, since you can't build a subclass!
60 public class Runtime
62 /**
63 * The library path, to search when loading libraries. We can also safely use
64 * this as a lock for synchronization.
66 private final String[] libpath;
68 static
70 init();
73 /**
74 * The thread that started the exit sequence. Access to this field must
75 * be thread-safe; lock on libpath to avoid deadlock with user code.
76 * <code>runFinalization()</code> may want to look at this to see if ALL
77 * finalizers should be run, because the virtual machine is about to halt.
79 private Thread exitSequence;
81 /**
82 * All shutdown hooks. This is initialized lazily, and set to null once all
83 * shutdown hooks have run. Access to this field must be thread-safe; lock
84 * on libpath to avoid deadlock with user code.
86 private Set shutdownHooks;
88 /** True if we should finalize on exit. */
89 private boolean finalizeOnExit;
91 /**
92 * The one and only runtime instance.
94 private static final Runtime current = new Runtime();
96 /**
97 * Not instantiable by a user, this should only create one instance.
99 private Runtime()
101 if (current != null)
102 throw new InternalError("Attempt to recreate Runtime");
104 // We don't use libpath in the libgcj implementation. We still
105 // set it to something to allow the various synchronizations to
106 // work.
107 libpath = new String[0];
111 * Get the current Runtime object for this JVM. This is necessary to access
112 * the many instance methods of this class.
114 * @return the current Runtime object
116 public static Runtime getRuntime()
118 return current;
122 * Exit the Java runtime. This method will either throw a SecurityException
123 * or it will never return. The status code is returned to the system; often
124 * a non-zero status code indicates an abnormal exit. Of course, there is a
125 * security check, <code>checkExit(status)</code>.
127 * <p>First, all shutdown hooks are run, in unspecified order, and
128 * concurrently. Next, if finalization on exit has been enabled, all pending
129 * finalizers are run. Finally, the system calls <code>halt</code>.</p>
131 * <p>If this is run a second time after shutdown has already started, there
132 * are two actions. If shutdown hooks are still executing, it blocks
133 * indefinitely. Otherwise, if the status is nonzero it halts immediately;
134 * if it is zero, it blocks indefinitely. This is typically called by
135 * <code>System.exit</code>.</p>
137 * @param status the status to exit with
138 * @throws SecurityException if permission is denied
139 * @see #addShutdownHook(Thread)
140 * @see #runFinalizersOnExit(boolean)
141 * @see #runFinalization()
142 * @see #halt(int)
144 public void exit(int status)
146 SecurityManager sm = SecurityManager.current; // Be thread-safe!
147 if (sm != null)
148 sm.checkExit(status);
149 boolean first = false;
150 synchronized (libpath) // Synch on libpath, not this, to avoid deadlock.
152 if (exitSequence == null)
154 first = true;
155 exitSequence = Thread.currentThread();
156 if (shutdownHooks != null)
158 Iterator i = shutdownHooks.iterator();
159 while (i.hasNext()) // Start all shutdown hooks.
162 ((Thread) i.next()).start();
164 catch (IllegalThreadStateException e)
166 i.remove();
171 if (first)
173 if (shutdownHooks != null)
175 // Check progress of all shutdown hooks. As a hook completes,
176 // remove it from the set. If a hook calls exit, it removes
177 // itself from the set, then waits indefinitely on the
178 // exitSequence thread. Once the set is empty, set it to null to
179 // signal all finalizer threads that halt may be called.
180 while (! shutdownHooks.isEmpty())
182 Thread[] hooks;
183 synchronized (libpath)
185 hooks = new Thread[shutdownHooks.size()];
186 shutdownHooks.toArray(hooks);
188 for (int i = hooks.length; --i >= 0; )
189 if (! hooks[i].isAlive())
190 synchronized (libpath)
192 shutdownHooks.remove(hooks[i]);
196 Thread.sleep(1); // Give other threads a chance.
198 catch (InterruptedException e)
200 // Ignore, the next loop just starts sooner.
203 synchronized (libpath)
205 shutdownHooks = null;
208 // XXX Right now, it is the VM that knows whether runFinalizersOnExit
209 // is true; so the VM must look at exitSequence to decide whether
210 // this should be run on every object.
211 runFinalization();
213 else
214 synchronized (libpath)
216 if (shutdownHooks != null)
218 shutdownHooks.remove(Thread.currentThread());
219 status = 0; // Change status to enter indefinite wait.
223 if (first || status > 0)
224 halt(status);
225 while (true)
228 exitSequence.join();
230 catch (InterruptedException e)
232 // Ignore, we've suspended indefinitely to let all shutdown
233 // hooks complete, and to let any non-zero exits through, because
234 // this is a duplicate call to exit(0).
239 * Register a new shutdown hook. This is invoked when the program exits
240 * normally (because all non-daemon threads ended, or because
241 * <code>System.exit</code> was invoked), or when the user terminates
242 * the virtual machine (such as by typing ^C, or logging off). There is
243 * a security check to add hooks,
244 * <code>RuntimePermission("shutdownHooks")</code>.
246 * <p>The hook must be an initialized, but unstarted Thread. The threads
247 * are run concurrently, and started in an arbitrary order; and user
248 * threads or daemons may still be running. Once shutdown hooks have
249 * started, they must all complete, or else you must use <code>halt</code>,
250 * to actually finish the shutdown sequence. Attempts to modify hooks
251 * after shutdown has started result in IllegalStateExceptions.</p>
253 * <p>It is imperative that you code shutdown hooks defensively, as you
254 * do not want to deadlock, and have no idea what other hooks will be
255 * running concurrently. It is also a good idea to finish quickly, as the
256 * virtual machine really wants to shut down!</p>
258 * <p>There are no guarantees that such hooks will run, as there are ways
259 * to forcibly kill a process. But in such a drastic case, shutdown hooks
260 * would do little for you in the first place.</p>
262 * @param hook an initialized, unstarted Thread
263 * @throws IllegalArgumentException if the hook is already registered or run
264 * @throws IllegalStateException if the virtual machine is already in
265 * the shutdown sequence
266 * @throws SecurityException if permission is denied
267 * @since 1.3
268 * @see #removeShutdownHook(Thread)
269 * @see #exit(int)
270 * @see #halt(int)
272 public void addShutdownHook(Thread hook)
274 SecurityManager sm = SecurityManager.current; // Be thread-safe!
275 if (sm != null)
276 sm.checkPermission(new RuntimePermission("shutdownHooks"));
277 if (hook.isAlive() || hook.getThreadGroup() == null)
278 throw new IllegalArgumentException("The hook thread " + hook + " must not have been already run or started");
279 synchronized (libpath)
281 if (exitSequence != null)
282 throw new IllegalStateException("The Virtual Machine is exiting. It is not possible anymore to add any hooks");
283 if (shutdownHooks == null)
284 shutdownHooks = new HashSet(); // Lazy initialization.
285 if (! shutdownHooks.add(hook))
286 throw new IllegalArgumentException(hook.toString() + " had already been inserted");
291 * De-register a shutdown hook. As when you registered it, there is a
292 * security check to remove hooks,
293 * <code>RuntimePermission("shutdownHooks")</code>.
295 * @param hook the hook to remove
296 * @return true if the hook was successfully removed, false if it was not
297 * registered in the first place
298 * @throws IllegalStateException if the virtual machine is already in
299 * the shutdown sequence
300 * @throws SecurityException if permission is denied
301 * @since 1.3
302 * @see #addShutdownHook(Thread)
303 * @see #exit(int)
304 * @see #halt(int)
306 public boolean removeShutdownHook(Thread hook)
308 SecurityManager sm = SecurityManager.current; // Be thread-safe!
309 if (sm != null)
310 sm.checkPermission(new RuntimePermission("shutdownHooks"));
311 synchronized (libpath)
313 if (exitSequence != null)
314 throw new IllegalStateException();
315 if (shutdownHooks != null)
316 return shutdownHooks.remove(hook);
318 return false;
322 * Forcibly terminate the virtual machine. This call never returns. It is
323 * much more severe than <code>exit</code>, as it bypasses all shutdown
324 * hooks and initializers. Use caution in calling this! Of course, there is
325 * a security check, <code>checkExit(status)</code>.
327 * @param status the status to exit with
328 * @throws SecurityException if permission is denied
329 * @since 1.3
330 * @see #exit(int)
331 * @see #addShutdownHook(Thread)
333 public void halt(int status)
335 SecurityManager sm = SecurityManager.current; // Be thread-safe!
336 if (sm != null)
337 sm.checkExit(status);
338 exitInternal(status);
342 * Tell the VM to run the finalize() method on every single Object before
343 * it exits. Note that the JVM may still exit abnormally and not perform
344 * this, so you still don't have a guarantee. And besides that, this is
345 * inherently unsafe in multi-threaded code, as it may result in deadlock
346 * as multiple threads compete to manipulate objects. This value defaults to
347 * <code>false</code>. There is a security check, <code>checkExit(0)</code>.
349 * @param finalizeOnExit whether to finalize all Objects on exit
350 * @throws SecurityException if permission is denied
351 * @see #exit(int)
352 * @see #gc()
353 * @since 1.1
354 * @deprecated never rely on finalizers to do a clean, thread-safe,
355 * mop-up from your code
357 public static void runFinalizersOnExit(boolean finalizeOnExit)
359 SecurityManager sm = SecurityManager.current; // Be thread-safe!
360 if (sm != null)
361 sm.checkExit(0);
362 current.finalizeOnExit = finalizeOnExit;
366 * Create a new subprocess with the specified command line. Calls
367 * <code>exec(cmdline, null, null)</code>. A security check is performed,
368 * <code>checkExec</code>.
370 * @param cmdline the command to call
371 * @return the Process object
372 * @throws SecurityException if permission is denied
373 * @throws IOException if an I/O error occurs
374 * @throws NullPointerException if cmdline is null
375 * @throws IndexOutOfBoundsException if cmdline is ""
377 public Process exec(String cmdline) throws IOException
379 return exec(cmdline, null, null);
383 * Create a new subprocess with the specified command line and environment.
384 * If the environment is null, the process inherits the environment of
385 * this process. Calls <code>exec(cmdline, env, null)</code>. A security
386 * check is performed, <code>checkExec</code>.
388 * @param cmdline the command to call
389 * @param env the environment to use, in the format name=value
390 * @return the Process object
391 * @throws SecurityException if permission is denied
392 * @throws IOException if an I/O error occurs
393 * @throws NullPointerException if cmdline is null, or env has null entries
394 * @throws IndexOutOfBoundsException if cmdline is ""
396 public Process exec(String cmdline, String[] env) throws IOException
398 return exec(cmdline, env, null);
402 * Create a new subprocess with the specified command line, environment, and
403 * working directory. If the environment is null, the process inherits the
404 * environment of this process. If the directory is null, the process uses
405 * the current working directory. This splits cmdline into an array, using
406 * the default StringTokenizer, then calls
407 * <code>exec(cmdArray, env, dir)</code>. A security check is performed,
408 * <code>checkExec</code>.
410 * @param cmdline the command to call
411 * @param env the environment to use, in the format name=value
412 * @param dir the working directory to use
413 * @return the Process object
414 * @throws SecurityException if permission is denied
415 * @throws IOException if an I/O error occurs
416 * @throws NullPointerException if cmdline is null, or env has null entries
417 * @throws IndexOutOfBoundsException if cmdline is ""
418 * @since 1.3
420 public Process exec(String cmdline, String[] env, File dir)
421 throws IOException
423 StringTokenizer t = new StringTokenizer(cmdline);
424 String[] cmd = new String[t.countTokens()];
425 for (int i = 0; i < cmd.length; i++)
426 cmd[i] = t.nextToken();
427 return exec(cmd, env, dir);
431 * Create a new subprocess with the specified command line, already
432 * tokenized. Calls <code>exec(cmd, null, null)</code>. A security check
433 * is performed, <code>checkExec</code>.
435 * @param cmd the command to call
436 * @return the Process object
437 * @throws SecurityException if permission is denied
438 * @throws IOException if an I/O error occurs
439 * @throws NullPointerException if cmd is null, or has null entries
440 * @throws IndexOutOfBoundsException if cmd is length 0
442 public Process exec(String[] cmd) throws IOException
444 return exec(cmd, null, null);
448 * Create a new subprocess with the specified command line, already
449 * tokenized, and specified environment. If the environment is null, the
450 * process inherits the environment of this process. Calls
451 * <code>exec(cmd, env, null)</code>. A security check is performed,
452 * <code>checkExec</code>.
454 * @param cmd the command to call
455 * @param env the environment to use, in the format name=value
456 * @return the Process object
457 * @throws SecurityException if permission is denied
458 * @throws IOException if an I/O error occurs
459 * @throws NullPointerException if cmd is null, or cmd or env has null
460 * entries
461 * @throws IndexOutOfBoundsException if cmd is length 0
463 public Process exec(String[] cmd, String[] env) throws IOException
465 return exec(cmd, env, null);
469 * Create a new subprocess with the specified command line, already
470 * tokenized, and the specified environment and working directory. If the
471 * environment is null, the process inherits the environment of this
472 * process. If the directory is null, the process uses the current working
473 * directory. A security check is performed, <code>checkExec</code>.
475 * @param cmd the command to call
476 * @param env the environment to use, in the format name=value
477 * @param dir the working directory to use
478 * @return the Process object
479 * @throws SecurityException if permission is denied
480 * @throws IOException if an I/O error occurs
481 * @throws NullPointerException if cmd is null, or cmd or env has null
482 * entries
483 * @throws IndexOutOfBoundsException if cmd is length 0
484 * @since 1.3
486 public Process exec(String[] cmd, String[] env, File dir)
487 throws IOException
489 SecurityManager sm = SecurityManager.current; // Be thread-safe!
490 if (sm != null)
491 sm.checkExec(cmd[0]);
492 return execInternal(cmd, env, dir);
496 * Returns the number of available processors currently available to the
497 * virtual machine. This number may change over time; so a multi-processor
498 * program want to poll this to determine maximal resource usage.
500 * @return the number of processors available, at least 1
502 public native int availableProcessors();
505 * Find out how much memory is still free for allocating Objects on the heap.
507 * @return the number of bytes of free memory for more Objects
509 public native long freeMemory();
512 * Find out how much memory total is available on the heap for allocating
513 * Objects.
515 * @return the total number of bytes of memory for Objects
517 public native long totalMemory();
520 * Returns the maximum amount of memory the virtual machine can attempt to
521 * use. This may be <code>Long.MAX_VALUE</code> if there is no inherent
522 * limit (or if you really do have a 8 exabyte memory!).
524 * @return the maximum number of bytes the virtual machine will attempt
525 * to allocate
527 public native long maxMemory();
530 * Run the garbage collector. This method is more of a suggestion than
531 * anything. All this method guarantees is that the garbage collector will
532 * have "done its best" by the time it returns. Notice that garbage
533 * collection takes place even without calling this method.
535 public native void gc();
538 * Run finalization on all Objects that are waiting to be finalized. Again,
539 * a suggestion, though a stronger one than {@link #gc()}. This calls the
540 * <code>finalize</code> method of all objects waiting to be collected.
542 * @see #finalize()
544 public native void runFinalization();
547 * Tell the VM to trace every bytecode instruction that executes (print out
548 * a trace of it). No guarantees are made as to where it will be printed,
549 * and the VM is allowed to ignore this request.
551 * @param on whether to turn instruction tracing on
553 public native void traceInstructions(boolean on);
556 * Tell the VM to trace every method call that executes (print out a trace
557 * of it). No guarantees are made as to where it will be printed, and the
558 * VM is allowed to ignore this request.
560 * @param on whether to turn method tracing on
562 public native void traceMethodCalls(boolean on);
565 * Load a native library using the system-dependent filename. This is similar
566 * to loadLibrary, except the only name mangling done is inserting "_g"
567 * before the final ".so" if the VM was invoked by the name "java_g". There
568 * may be a security check, of <code>checkLink</code>.
570 * @param filename the file to load
571 * @throws SecurityException if permission is denied
572 * @throws UnsatisfiedLinkError if the library is not found
574 public void load(String filename)
576 SecurityManager sm = SecurityManager.current; // Be thread-safe!
577 if (sm != null)
578 sm.checkLink(filename);
579 _load(filename, false);
583 * Load a native library using a system-independent "short name" for the
584 * library. It will be transformed to a correct filename in a
585 * system-dependent manner (for example, in Windows, "mylib" will be turned
586 * into "mylib.dll"). This is done as follows: if the context that called
587 * load has a ClassLoader cl, then <code>cl.findLibrary(libpath)</code> is
588 * used to convert the name. If that result was null, or there was no class
589 * loader, this searches each directory of the system property
590 * <code>java.library.path</code> for a file named
591 * <code>System.mapLibraryName(libname)</code>. There may be a security
592 * check, of <code>checkLink</code>.
594 * @param libname the library to load
596 * @throws SecurityException if permission is denied
597 * @throws UnsatisfiedLinkError if the library is not found
599 * @see System#mapLibraryName(String)
600 * @see ClassLoader#findLibrary(String)
602 public void loadLibrary(String libname)
604 // This is different from the Classpath implementation, but I
605 // believe it is more correct.
606 SecurityManager sm = SecurityManager.current; // Be thread-safe!
607 if (sm != null)
608 sm.checkLink(libname);
609 _load(libname, true);
613 * Return a localized version of this InputStream, meaning all characters
614 * are localized before they come out the other end.
616 * @param in the stream to localize
617 * @return the localized stream
618 * @deprecated <code>InputStreamReader</code> is the preferred way to read
619 * local encodings
621 public InputStream getLocalizedInputStream(InputStream in)
623 return in;
627 * Return a localized version of this OutputStream, meaning all characters
628 * are localized before they are sent to the other end.
630 * @param out the stream to localize
631 * @return the localized stream
632 * @deprecated <code>OutputStreamWriter</code> is the preferred way to write
633 * local encodings
635 public OutputStream getLocalizedOutputStream(OutputStream out)
637 return out;
641 * Native method that actually shuts down the virtual machine.
643 * @param status the status to end the process with
645 native void exitInternal(int status);
648 * Load a file. If it has already been loaded, do nothing. The name has
649 * already been mapped to a true filename.
651 * @param filename the file to load
652 * @param do_search True if we should search the load path for the file
654 native void _load(String filename, boolean do_search);
657 *This is a helper function for the ClassLoader which can load
658 * compiled libraries. Returns true if library (which is just the
659 * base name -- path searching is done by this function) was loaded,
660 * false otherwise.
662 native boolean loadLibraryInternal(String libname);
665 * A helper for Runtime static initializer which does some internal native
666 * initialization.
668 private static native void init ();
671 * Map a system-independent "short name" to the full file name, and append
672 * it to the path.
673 * XXX This method is being replaced by System.mapLibraryName.
675 * @param pathname the path
676 * @param libname the short version of the library name
677 * @return the full filename
679 static native String nativeGetLibname(String pathname, String libname);
682 * Execute a process. The command line has already been tokenized, and
683 * the environment should contain name=value mappings. If directory is null,
684 * use the current working directory; otherwise start the process in that
685 * directory.
687 * @param cmd the non-null command tokens
688 * @param env the non-null environment setup
689 * @param dir the directory to use, may be null
690 * @return the newly created process
691 * @throws NullPointerException if cmd or env have null elements
692 * @throws IOException if the exec fails
694 native Process execInternal(String[] cmd, String[] env, File dir)
695 throws IOException;
696 } // class Runtime