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 26 package java.lang; 27 28 import java.io.*; 29 import java.util.StringTokenizer; 30 import sun.reflect.CallerSensitive; 31 import sun.reflect.Reflection; 32 33 /** 34 * Every Java application has a single instance of class 35 * <code>Runtime</code> that allows the application to interface with 36 * the environment in which the application is running. The current 37 * runtime can be obtained from the <code>getRuntime</code> method. 38 * <p> 39 * An application cannot create its own instance of this class. 40 * 41 * @author unascribed 42 * @see java.lang.Runtime#getRuntime() 43 * @since 1.0 44 */ 45 46 public class Runtime { 47 private static Runtime currentRuntime = new Runtime(); 48 49 /** 50 * Returns the runtime object associated with the current Java application. 51 * Most of the methods of class <code>Runtime</code> are instance 52 * methods and must be invoked with respect to the current runtime object. 53 * 54 * @return the <code>Runtime</code> object associated with the current 55 * Java application. 56 */ 57 public static Runtime getRuntime() { 58 return currentRuntime; 59 } 60 61 /** Don't let anyone else instantiate this class */ 62 private Runtime() {} 63 64 /** 65 * Terminates the currently running Java virtual machine by initiating its 66 * shutdown sequence. This method never returns normally. The argument 67 * serves as a status code; by convention, a nonzero status code indicates 68 * abnormal termination. 69 * 70 * <p> The virtual machine's shutdown sequence consists of two phases. In 71 * the first phase all registered {@link #addShutdownHook shutdown hooks}, 72 * if any, are started in some unspecified order and allowed to run 73 * concurrently until they finish. In the second phase all uninvoked 74 * finalizers are run if {@link #runFinalizersOnExit finalization-on-exit} 75 * has been enabled. Once this is done the virtual machine {@link #halt 76 * halts}. 77 * 78 * <p> If this method is invoked after the virtual machine has begun its 79 * shutdown sequence then if shutdown hooks are being run this method will 80 * block indefinitely. If shutdown hooks have already been run and on-exit 81 * finalization has been enabled then this method halts the virtual machine 82 * with the given status code if the status is nonzero; otherwise, it 83 * blocks indefinitely. 84 * 85 * <p> The <tt>{@link System#exit(int) System.exit}</tt> method is the 86 * conventional and convenient means of invoking this method. 87 * 88 * @param status 89 * Termination status. By convention, a nonzero status code 90 * indicates abnormal termination. 91 * 92 * @throws SecurityException 93 * If a security manager is present and its <tt>{@link 94 * SecurityManager#checkExit checkExit}</tt> method does not permit 95 * exiting with the specified status 96 * 97 * @see java.lang.SecurityException 98 * @see java.lang.SecurityManager#checkExit(int) 99 * @see #addShutdownHook 100 * @see #removeShutdownHook 101 * @see #runFinalizersOnExit 102 * @see #halt(int) 103 */ 104 public void exit(int status) { 105 SecurityManager security = System.getSecurityManager(); 106 if (security != null) { 107 security.checkExit(status); 108 } 109 Shutdown.exit(status); 110 } 111 112 /** 113 * Registers a new virtual-machine shutdown hook. 114 * 115 * <p> The Java virtual machine <i>shuts down</i> in response to two kinds 116 * of events: 117 * 118 * <ul> 119 * 120 * <li> The program <i>exits</i> normally, when the last non-daemon 121 * thread exits or when the <tt>{@link #exit exit}</tt> (equivalently, 122 * {@link System#exit(int) System.exit}) method is invoked, or 123 * 124 * <li> The virtual machine is <i>terminated</i> in response to a 125 * user interrupt, such as typing <tt>^C</tt>, or a system-wide event, 126 * such as user logoff or system shutdown. 127 * 128 * </ul> 129 * 130 * <p> A <i>shutdown hook</i> is simply an initialized but unstarted 131 * thread. When the virtual machine begins its shutdown sequence it will 132 * start all registered shutdown hooks in some unspecified order and let 133 * them run concurrently. When all the hooks have finished it will then 134 * run all uninvoked finalizers if finalization-on-exit has been enabled. 135 * Finally, the virtual machine will halt. Note that daemon threads will 136 * continue to run during the shutdown sequence, as will non-daemon threads 137 * if shutdown was initiated by invoking the <tt>{@link #exit exit}</tt> 138 * method. 139 * 140 * <p> Once the shutdown sequence has begun it can be stopped only by 141 * invoking the <tt>{@link #halt halt}</tt> method, which forcibly 142 * terminates the virtual machine. 143 * 144 * <p> Once the shutdown sequence has begun it is impossible to register a 145 * new shutdown hook or de-register a previously-registered hook. 146 * Attempting either of these operations will cause an 147 * <tt>{@link IllegalStateException}</tt> to be thrown. 148 * 149 * <p> Shutdown hooks run at a delicate time in the life cycle of a virtual 150 * machine and should therefore be coded defensively. They should, in 151 * particular, be written to be thread-safe and to avoid deadlocks insofar 152 * as possible. They should also not rely blindly upon services that may 153 * have registered their own shutdown hooks and therefore may themselves in 154 * the process of shutting down. Attempts to use other thread-based 155 * services such as the AWT event-dispatch thread, for example, may lead to 156 * deadlocks. 157 * 158 * <p> Shutdown hooks should also finish their work quickly. When a 159 * program invokes <tt>{@link #exit exit}</tt> the expectation is 160 * that the virtual machine will promptly shut down and exit. When the 161 * virtual machine is terminated due to user logoff or system shutdown the 162 * underlying operating system may only allow a fixed amount of time in 163 * which to shut down and exit. It is therefore inadvisable to attempt any 164 * user interaction or to perform a long-running computation in a shutdown 165 * hook. 166 * 167 * <p> Uncaught exceptions are handled in shutdown hooks just as in any 168 * other thread, by invoking the <tt>{@link ThreadGroup#uncaughtException 169 * uncaughtException}</tt> method of the thread's <tt>{@link 170 * ThreadGroup}</tt> object. The default implementation of this method 171 * prints the exception's stack trace to <tt>{@link System#err}</tt> and 172 * terminates the thread; it does not cause the virtual machine to exit or 173 * halt. 174 * 175 * <p> In rare circumstances the virtual machine may <i>abort</i>, that is, 176 * stop running without shutting down cleanly. This occurs when the 177 * virtual machine is terminated externally, for example with the 178 * <tt>SIGKILL</tt> signal on Unix or the <tt>TerminateProcess</tt> call on 179 * Microsoft Windows. The virtual machine may also abort if a native 180 * method goes awry by, for example, corrupting internal data structures or 181 * attempting to access nonexistent memory. If the virtual machine aborts 182 * then no guarantee can be made about whether or not any shutdown hooks 183 * will be run. 184 * 185 * @param hook 186 * An initialized but unstarted <tt>{@link Thread}</tt> object 187 * 188 * @throws IllegalArgumentException 189 * If the specified hook has already been registered, 190 * or if it can be determined that the hook is already running or 191 * has already been run 192 * 193 * @throws IllegalStateException 194 * If the virtual machine is already in the process 195 * of shutting down 196 * 197 * @throws SecurityException 198 * If a security manager is present and it denies 199 * <tt>{@link RuntimePermission}("shutdownHooks")</tt> 200 * 201 * @see #removeShutdownHook 202 * @see #halt(int) 203 * @see #exit(int) 204 * @since 1.3 205 */ 206 public void addShutdownHook(Thread hook) { 207 SecurityManager sm = System.getSecurityManager(); 208 if (sm != null) { 209 sm.checkPermission(new RuntimePermission("shutdownHooks")); 210 } 211 ApplicationShutdownHooks.add(hook); 212 } 213 214 /** 215 * De-registers a previously-registered virtual-machine shutdown hook. <p> 216 * 217 * @param hook the hook to remove 218 * @return <tt>true</tt> if the specified hook had previously been 219 * registered and was successfully de-registered, <tt>false</tt> 220 * otherwise. 221 * 222 * @throws IllegalStateException 223 * If the virtual machine is already in the process of shutting 224 * down 225 * 226 * @throws SecurityException 227 * If a security manager is present and it denies 228 * <tt>{@link RuntimePermission}("shutdownHooks")</tt> 229 * 230 * @see #addShutdownHook 231 * @see #exit(int) 232 * @since 1.3 233 */ 234 public boolean removeShutdownHook(Thread hook) { 235 SecurityManager sm = System.getSecurityManager(); 236 if (sm != null) { 237 sm.checkPermission(new RuntimePermission("shutdownHooks")); 238 } 239 return ApplicationShutdownHooks.remove(hook); 240 } 241 242 /** 243 * Forcibly terminates the currently running Java virtual machine. This 244 * method never returns normally. 245 * 246 * <p> This method should be used with extreme caution. Unlike the 247 * <tt>{@link #exit exit}</tt> method, this method does not cause shutdown 248 * hooks to be started and does not run uninvoked finalizers if 249 * finalization-on-exit has been enabled. If the shutdown sequence has 250 * already been initiated then this method does not wait for any running 251 * shutdown hooks or finalizers to finish their work. 252 * 253 * @param status 254 * Termination status. By convention, a nonzero status code 255 * indicates abnormal termination. If the <tt>{@link Runtime#exit 256 * exit}</tt> (equivalently, <tt>{@link System#exit(int) 257 * System.exit}</tt>) method has already been invoked then this 258 * status code will override the status code passed to that method. 259 * 260 * @throws SecurityException 261 * If a security manager is present and its <tt>{@link 262 * SecurityManager#checkExit checkExit}</tt> method does not permit 263 * an exit with the specified status 264 * 265 * @see #exit 266 * @see #addShutdownHook 267 * @see #removeShutdownHook 268 * @since 1.3 269 */ 270 public void halt(int status) { 271 SecurityManager sm = System.getSecurityManager(); 272 if (sm != null) { 273 sm.checkExit(status); 274 } 275 Shutdown.halt(status); 276 } 277 278 /** 279 * Enable or disable finalization on exit; doing so specifies that the 280 * finalizers of all objects that have finalizers that have not yet been 281 * automatically invoked are to be run before the Java runtime exits. 282 * By default, finalization on exit is disabled. 283 * 284 * <p>If there is a security manager, 285 * its <code>checkExit</code> method is first called 286 * with 0 as its argument to ensure the exit is allowed. 287 * This could result in a SecurityException. 288 * 289 * @param value true to enable finalization on exit, false to disable 290 * @deprecated This method is inherently unsafe. It may result in 291 * finalizers being called on live objects while other threads are 292 * concurrently manipulating those objects, resulting in erratic 293 * behavior or deadlock. 294 * 295 * @throws SecurityException 296 * if a security manager exists and its <code>checkExit</code> 297 * method doesn't allow the exit. 298 * 299 * @see java.lang.Runtime#exit(int) 300 * @see java.lang.Runtime#gc() 301 * @see java.lang.SecurityManager#checkExit(int) 302 * @since 1.1 303 */ 304 @Deprecated 305 public static void runFinalizersOnExit(boolean value) { 306 SecurityManager security = System.getSecurityManager(); 307 if (security != null) { 308 try { 309 security.checkExit(0); 310 } catch (SecurityException e) { 311 throw new SecurityException("runFinalizersOnExit"); 312 } 313 } 314 Shutdown.setRunFinalizersOnExit(value); 315 } 316 317 /** 318 * Executes the specified string command in a separate process. 319 * 320 * <p>This is a convenience method. An invocation of the form 321 * <tt>exec(command)</tt> 322 * behaves in exactly the same way as the invocation 323 * <tt>{@link #exec(String, String[], File) exec}(command, null, null)</tt>. 324 * 325 * @param command a specified system command. 326 * 327 * @return A new {@link Process} object for managing the subprocess 328 * 329 * @throws SecurityException 330 * If a security manager exists and its 331 * {@link SecurityManager#checkExec checkExec} 332 * method doesn't allow creation of the subprocess 333 * 334 * @throws IOException 335 * If an I/O error occurs 336 * 337 * @throws NullPointerException 338 * If <code>command</code> is <code>null</code> 339 * 340 * @throws IllegalArgumentException 341 * If <code>command</code> is empty 342 * 343 * @see #exec(String[], String[], File) 344 * @see ProcessBuilder 345 */ 346 public Process exec(String command) throws IOException { 347 return exec(command, null, null); 348 } 349 350 /** 351 * Executes the specified string command in a separate process with the 352 * specified environment. 353 * 354 * <p>This is a convenience method. An invocation of the form 355 * <tt>exec(command, envp)</tt> 356 * behaves in exactly the same way as the invocation 357 * <tt>{@link #exec(String, String[], File) exec}(command, envp, null)</tt>. 358 * 359 * @param command a specified system command. 360 * 361 * @param envp array of strings, each element of which 362 * has environment variable settings in the format 363 * <i>name</i>=<i>value</i>, or 364 * <tt>null</tt> if the subprocess should inherit 365 * the environment of the current process. 366 * 367 * @return A new {@link Process} object for managing the subprocess 368 * 369 * @throws SecurityException 370 * If a security manager exists and its 371 * {@link SecurityManager#checkExec checkExec} 372 * method doesn't allow creation of the subprocess 373 * 374 * @throws IOException 375 * If an I/O error occurs 376 * 377 * @throws NullPointerException 378 * If <code>command</code> is <code>null</code>, 379 * or one of the elements of <code>envp</code> is <code>null</code> 380 * 381 * @throws IllegalArgumentException 382 * If <code>command</code> is empty 383 * 384 * @see #exec(String[], String[], File) 385 * @see ProcessBuilder 386 */ 387 public Process exec(String command, String[] envp) throws IOException { 388 return exec(command, envp, null); 389 } 390 391 /** 392 * Executes the specified string command in a separate process with the 393 * specified environment and working directory. 394 * 395 * <p>This is a convenience method. An invocation of the form 396 * <tt>exec(command, envp, dir)</tt> 397 * behaves in exactly the same way as the invocation 398 * <tt>{@link #exec(String[], String[], File) exec}(cmdarray, envp, dir)</tt>, 399 * where <code>cmdarray</code> is an array of all the tokens in 400 * <code>command</code>. 401 * 402 * <p>More precisely, the <code>command</code> string is broken 403 * into tokens using a {@link StringTokenizer} created by the call 404 * <code>new {@link StringTokenizer}(command)</code> with no 405 * further modification of the character categories. The tokens 406 * produced by the tokenizer are then placed in the new string 407 * array <code>cmdarray</code>, in the same order. 408 * 409 * @param command a specified system command. 410 * 411 * @param envp array of strings, each element of which 412 * has environment variable settings in the format 413 * <i>name</i>=<i>value</i>, or 414 * <tt>null</tt> if the subprocess should inherit 415 * the environment of the current process. 416 * 417 * @param dir the working directory of the subprocess, or 418 * <tt>null</tt> if the subprocess should inherit 419 * the working directory of the current process. 420 * 421 * @return A new {@link Process} object for managing the subprocess 422 * 423 * @throws SecurityException 424 * If a security manager exists and its 425 * {@link SecurityManager#checkExec checkExec} 426 * method doesn't allow creation of the subprocess 427 * 428 * @throws IOException 429 * If an I/O error occurs 430 * 431 * @throws NullPointerException 432 * If <code>command</code> is <code>null</code>, 433 * or one of the elements of <code>envp</code> is <code>null</code> 434 * 435 * @throws IllegalArgumentException 436 * If <code>command</code> is empty 437 * 438 * @see ProcessBuilder 439 * @since 1.3 440 */ 441 public Process exec(String command, String[] envp, File dir) 442 throws IOException { 443 if (command.length() == 0) 444 throw new IllegalArgumentException("Empty command"); 445 446 StringTokenizer st = new StringTokenizer(command); 447 String[] cmdarray = new String[st.countTokens()]; 448 for (int i = 0; st.hasMoreTokens(); i++) 449 cmdarray[i] = st.nextToken(); 450 return exec(cmdarray, envp, dir); 451 } 452 453 /** 454 * Executes the specified command and arguments in a separate process. 455 * 456 * <p>This is a convenience method. An invocation of the form 457 * <tt>exec(cmdarray)</tt> 458 * behaves in exactly the same way as the invocation 459 * <tt>{@link #exec(String[], String[], File) exec}(cmdarray, null, null)</tt>. 460 * 461 * @param cmdarray array containing the command to call and 462 * its arguments. 463 * 464 * @return A new {@link Process} object for managing the subprocess 465 * 466 * @throws SecurityException 467 * If a security manager exists and its 468 * {@link SecurityManager#checkExec checkExec} 469 * method doesn't allow creation of the subprocess 470 * 471 * @throws IOException 472 * If an I/O error occurs 473 * 474 * @throws NullPointerException 475 * If <code>cmdarray</code> is <code>null</code>, 476 * or one of the elements of <code>cmdarray</code> is <code>null</code> 477 * 478 * @throws IndexOutOfBoundsException 479 * If <code>cmdarray</code> is an empty array 480 * (has length <code>0</code>) 481 * 482 * @see ProcessBuilder 483 */ 484 public Process exec(String cmdarray[]) throws IOException { 485 return exec(cmdarray, null, null); 486 } 487 488 /** 489 * Executes the specified command and arguments in a separate process 490 * with the specified environment. 491 * 492 * <p>This is a convenience method. An invocation of the form 493 * <tt>exec(cmdarray, envp)</tt> 494 * behaves in exactly the same way as the invocation 495 * <tt>{@link #exec(String[], String[], File) exec}(cmdarray, envp, null)</tt>. 496 * 497 * @param cmdarray array containing the command to call and 498 * its arguments. 499 * 500 * @param envp array of strings, each element of which 501 * has environment variable settings in the format 502 * <i>name</i>=<i>value</i>, or 503 * <tt>null</tt> if the subprocess should inherit 504 * the environment of the current process. 505 * 506 * @return A new {@link Process} object for managing the subprocess 507 * 508 * @throws SecurityException 509 * If a security manager exists and its 510 * {@link SecurityManager#checkExec checkExec} 511 * method doesn't allow creation of the subprocess 512 * 513 * @throws IOException 514 * If an I/O error occurs 515 * 516 * @throws NullPointerException 517 * If <code>cmdarray</code> is <code>null</code>, 518 * or one of the elements of <code>cmdarray</code> is <code>null</code>, 519 * or one of the elements of <code>envp</code> is <code>null</code> 520 * 521 * @throws IndexOutOfBoundsException 522 * If <code>cmdarray</code> is an empty array 523 * (has length <code>0</code>) 524 * 525 * @see ProcessBuilder 526 */ 527 public Process exec(String[] cmdarray, String[] envp) throws IOException { 528 return exec(cmdarray, envp, null); 529 } 530 531 532 /** 533 * Executes the specified command and arguments in a separate process with 534 * the specified environment and working directory. 535 * 536 * <p>Given an array of strings <code>cmdarray</code>, representing the 537 * tokens of a command line, and an array of strings <code>envp</code>, 538 * representing "environment" variable settings, this method creates 539 * a new process in which to execute the specified command. 540 * 541 * <p>This method checks that <code>cmdarray</code> is a valid operating 542 * system command. Which commands are valid is system-dependent, 543 * but at the very least the command must be a non-empty list of 544 * non-null strings. 545 * 546 * <p>If <tt>envp</tt> is <tt>null</tt>, the subprocess inherits the 547 * environment settings of the current process. 548 * 549 * <p>A minimal set of system dependent environment variables may 550 * be required to start a process on some operating systems. 551 * As a result, the subprocess may inherit additional environment variable 552 * settings beyond those in the specified environment. 553 * 554 * <p>{@link ProcessBuilder#start()} is now the preferred way to 555 * start a process with a modified environment. 556 * 557 * <p>The working directory of the new subprocess is specified by <tt>dir</tt>. 558 * If <tt>dir</tt> is <tt>null</tt>, the subprocess inherits the 559 * current working directory of the current process. 560 * 561 * <p>If a security manager exists, its 562 * {@link SecurityManager#checkExec checkExec} 563 * method is invoked with the first component of the array 564 * <code>cmdarray</code> as its argument. This may result in a 565 * {@link SecurityException} being thrown. 566 * 567 * <p>Starting an operating system process is highly system-dependent. 568 * Among the many things that can go wrong are: 569 * <ul> 570 * <li>The operating system program file was not found. 571 * <li>Access to the program file was denied. 572 * <li>The working directory does not exist. 573 * </ul> 574 * 575 * <p>In such cases an exception will be thrown. The exact nature 576 * of the exception is system-dependent, but it will always be a 577 * subclass of {@link IOException}. 578 * 579 * <p>If the operating system does not support the creation of 580 * processes, an {@link UnsupportedOperationException} will be thrown. 581 * 582 * 583 * @param cmdarray array containing the command to call and 584 * its arguments. 585 * 586 * @param envp array of strings, each element of which 587 * has environment variable settings in the format 588 * <i>name</i>=<i>value</i>, or 589 * <tt>null</tt> if the subprocess should inherit 590 * the environment of the current process. 591 * 592 * @param dir the working directory of the subprocess, or 593 * <tt>null</tt> if the subprocess should inherit 594 * the working directory of the current process. 595 * 596 * @return A new {@link Process} object for managing the subprocess 597 * 598 * @throws SecurityException 599 * If a security manager exists and its 600 * {@link SecurityManager#checkExec checkExec} 601 * method doesn't allow creation of the subprocess 602 * 603 * @throws UnsupportedOperationException 604 * If the operating system does not support the creation of processes. 605 * 606 * @throws IOException 607 * If an I/O error occurs 608 * 609 * @throws NullPointerException 610 * If <code>cmdarray</code> is <code>null</code>, 611 * or one of the elements of <code>cmdarray</code> is <code>null</code>, 612 * or one of the elements of <code>envp</code> is <code>null</code> 613 * 614 * @throws IndexOutOfBoundsException 615 * If <code>cmdarray</code> is an empty array 616 * (has length <code>0</code>) 617 * 618 * @see ProcessBuilder 619 * @since 1.3 620 */ 621 public Process exec(String[] cmdarray, String[] envp, File dir) 622 throws IOException { 623 return new ProcessBuilder(cmdarray) 624 .environment(envp) 625 .directory(dir) 626 .start(); 627 } 628 629 /** 630 * Returns the number of processors available to the Java virtual machine. 631 * 632 * <p> This value may change during a particular invocation of the virtual 633 * machine. Applications that are sensitive to the number of available 634 * processors should therefore occasionally poll this property and adjust 635 * their resource usage appropriately. </p> 636 * 637 * @return the maximum number of processors available to the virtual 638 * machine; never smaller than one 639 * @since 1.4 640 */ 641 public native int availableProcessors(); 642 643 /** 644 * Returns the amount of free memory in the Java Virtual Machine. 645 * Calling the 646 * <code>gc</code> method may result in increasing the value returned 647 * by <code>freeMemory.</code> 648 * 649 * @return an approximation to the total amount of memory currently 650 * available for future allocated objects, measured in bytes. 651 */ 652 public native long freeMemory(); 653 654 /** 655 * Returns the total amount of memory in the Java virtual machine. 656 * The value returned by this method may vary over time, depending on 657 * the host environment. 658 * <p> 659 * Note that the amount of memory required to hold an object of any 660 * given type may be implementation-dependent. 661 * 662 * @return the total amount of memory currently available for current 663 * and future objects, measured in bytes. 664 */ 665 public native long totalMemory(); 666 667 /** 668 * Returns the maximum amount of memory that the Java virtual machine will 669 * attempt to use. If there is no inherent limit then the value {@link 670 * java.lang.Long#MAX_VALUE} will be returned. 671 * 672 * @return the maximum amount of memory that the virtual machine will 673 * attempt to use, measured in bytes 674 * @since 1.4 675 */ 676 public native long maxMemory(); 677 678 /** 679 * Runs the garbage collector. 680 * Calling this method suggests that the Java virtual machine expend 681 * effort toward recycling unused objects in order to make the memory 682 * they currently occupy available for quick reuse. When control 683 * returns from the method call, the virtual machine has made 684 * its best effort to recycle all discarded objects. 685 * <p> 686 * The name <code>gc</code> stands for "garbage 687 * collector". The virtual machine performs this recycling 688 * process automatically as needed, in a separate thread, even if the 689 * <code>gc</code> method is not invoked explicitly. 690 * <p> 691 * The method {@link System#gc()} is the conventional and convenient 692 * means of invoking this method. 693 */ 694 public native void gc(); 695 696 /* Wormhole for calling java.lang.ref.Finalizer.runFinalization */ 697 private static native void runFinalization0(); 698 699 /** 700 * Runs the finalization methods of any objects pending finalization. 701 * Calling this method suggests that the Java virtual machine expend 702 * effort toward running the <code>finalize</code> methods of objects 703 * that have been found to be discarded but whose <code>finalize</code> 704 * methods have not yet been run. When control returns from the 705 * method call, the virtual machine has made a best effort to 706 * complete all outstanding finalizations. 707 * <p> 708 * The virtual machine performs the finalization process 709 * automatically as needed, in a separate thread, if the 710 * <code>runFinalization</code> method is not invoked explicitly. 711 * <p> 712 * The method {@link System#runFinalization()} is the conventional 713 * and convenient means of invoking this method. 714 * 715 * @see java.lang.Object#finalize() 716 */ 717 public void runFinalization() { 718 runFinalization0(); 719 } 720 721 /** 722 * Enables/Disables tracing of instructions. 723 * If the <code>boolean</code> argument is <code>true</code>, this 724 * method suggests that the Java virtual machine emit debugging 725 * information for each instruction in the virtual machine as it 726 * is executed. The format of this information, and the file or other 727 * output stream to which it is emitted, depends on the host environment. 728 * The virtual machine may ignore this request if it does not support 729 * this feature. The destination of the trace output is system 730 * dependent. 731 * <p> 732 * If the <code>boolean</code> argument is <code>false</code>, this 733 * method causes the virtual machine to stop performing the 734 * detailed instruction trace it is performing. 735 * 736 * @param on <code>true</code> to enable instruction tracing; 737 * <code>false</code> to disable this feature. 738 */ 739 public void traceInstructions(boolean on) { } 740 741 /** 742 * Enables/Disables tracing of method calls. 743 * If the <code>boolean</code> argument is <code>true</code>, this 744 * method suggests that the Java virtual machine emit debugging 745 * information for each method in the virtual machine as it is 746 * called. The format of this information, and the file or other output 747 * stream to which it is emitted, depends on the host environment. The 748 * virtual machine may ignore this request if it does not support 749 * this feature. 750 * <p> 751 * Calling this method with argument false suggests that the 752 * virtual machine cease emitting per-call debugging information. 753 * 754 * @param on <code>true</code> to enable instruction tracing; 755 * <code>false</code> to disable this feature. 756 */ 757 public void traceMethodCalls(boolean on) { } 758 759 /** 760 * Loads the native library specified by the filename argument. The filename 761 * argument must be an absolute path name. 762 * (for example 763 * <code>Runtime.getRuntime().load("/home/avh/lib/libX11.so");</code>). 764 * 765 * If the filename argument, when stripped of any platform-specific library 766 * prefix, path, and file extension, indicates a library whose name is, 767 * for example, L, and a native library called L is statically linked 768 * with the VM, then the JNI_OnLoad_L function exported by the library 769 * is invoked rather than attempting to load a dynamic library. 770 * A filename matching the argument does not have to exist in the file 771 * system. See the JNI Specification for more details. 772 * 773 * Otherwise, the filename argument is mapped to a native library image in 774 * an implementation-dependent manner. 775 * <p> 776 * First, if there is a security manager, its <code>checkLink</code> 777 * method is called with the <code>filename</code> as its argument. 778 * This may result in a security exception. 779 * <p> 780 * This is similar to the method {@link #loadLibrary(String)}, but it 781 * accepts a general file name as an argument rather than just a library 782 * name, allowing any file of native code to be loaded. 783 * <p> 784 * The method {@link System#load(String)} is the conventional and 785 * convenient means of invoking this method. 786 * 787 * @param filename the file to load. 788 * @exception SecurityException if a security manager exists and its 789 * <code>checkLink</code> method doesn't allow 790 * loading of the specified dynamic library 791 * @exception UnsatisfiedLinkError if either the filename is not an 792 * absolute path name, the native library is not statically 793 * linked with the VM, or the library cannot be mapped to 794 * a native library image by the host system. 795 * @exception NullPointerException if <code>filename</code> is 796 * <code>null</code> 797 * @see java.lang.Runtime#getRuntime() 798 * @see java.lang.SecurityException 799 * @see java.lang.SecurityManager#checkLink(java.lang.String) 800 */ 801 @CallerSensitive 802 public void load(String filename) { 803 load0(Reflection.getCallerClass(), filename); 804 } 805 806 synchronized void load0(Class<?> fromClass, String filename) { 807 SecurityManager security = System.getSecurityManager(); 808 if (security != null) { 809 security.checkLink(filename); 810 } 811 if (!(new File(filename).isAbsolute())) { 812 throw new UnsatisfiedLinkError( 813 "Expecting an absolute path of the library: " + filename); 814 } 815 ClassLoader.loadLibrary(fromClass, filename, true); 816 } 817 818 /** 819 * Loads the native library specified by the <code>libname</code> 820 * argument. The <code>libname</code> argument must not contain any platform 821 * specific prefix, file extension or path. If a native library 822 * called <code>libname</code> is statically linked with the VM, then the 823 * JNI_OnLoad_<code>libname</code> function exported by the library is invoked. 824 * See the JNI Specification for more details. 825 * 826 * Otherwise, the libname argument is loaded from a system library 827 * location and mapped to a native library image in an implementation- 828 * dependent manner. 829 * <p> 830 * First, if there is a security manager, its <code>checkLink</code> 831 * method is called with the <code>libname</code> as its argument. 832 * This may result in a security exception. 833 * <p> 834 * The method {@link System#loadLibrary(String)} is the conventional 835 * and convenient means of invoking this method. If native 836 * methods are to be used in the implementation of a class, a standard 837 * strategy is to put the native code in a library file (call it 838 * <code>LibFile</code>) and then to put a static initializer: 839 * <blockquote><pre> 840 * static { System.loadLibrary("LibFile"); } 841 * </pre></blockquote> 842 * within the class declaration. When the class is loaded and 843 * initialized, the necessary native code implementation for the native 844 * methods will then be loaded as well. 845 * <p> 846 * If this method is called more than once with the same library 847 * name, the second and subsequent calls are ignored. 848 * 849 * @param libname the name of the library. 850 * @exception SecurityException if a security manager exists and its 851 * <code>checkLink</code> method doesn't allow 852 * loading of the specified dynamic library 853 * @exception UnsatisfiedLinkError if either the libname argument 854 * contains a file path, the native library is not statically 855 * linked with the VM, or the library cannot be mapped to a 856 * native library image by the host system. 857 * @exception NullPointerException if <code>libname</code> is 858 * <code>null</code> 859 * @see java.lang.SecurityException 860 * @see java.lang.SecurityManager#checkLink(java.lang.String) 861 */ 862 @CallerSensitive 863 public void loadLibrary(String libname) { 864 loadLibrary0(Reflection.getCallerClass(), libname); 865 } 866 867 synchronized void loadLibrary0(Class<?> fromClass, String libname) { 868 SecurityManager security = System.getSecurityManager(); 869 if (security != null) { 870 security.checkLink(libname); 871 } 872 if (libname.indexOf((int)File.separatorChar) != -1) { 873 throw new UnsatisfiedLinkError( 874 "Directory separator should not appear in library name: " + libname); 875 } 876 ClassLoader.loadLibrary(fromClass, libname, false); 877 } 878 879 /** 880 * Creates a localized version of an input stream. This method takes 881 * an <code>InputStream</code> and returns an <code>InputStream</code> 882 * equivalent to the argument in all respects except that it is 883 * localized: as characters in the local character set are read from 884 * the stream, they are automatically converted from the local 885 * character set to Unicode. 886 * <p> 887 * If the argument is already a localized stream, it may be returned 888 * as the result. 889 * 890 * @param in InputStream to localize 891 * @return a localized input stream 892 * @see java.io.InputStream 893 * @see java.io.BufferedReader#BufferedReader(java.io.Reader) 894 * @see java.io.InputStreamReader#InputStreamReader(java.io.InputStream) 895 * @deprecated As of JDK 1.1, the preferred way to translate a byte 896 * stream in the local encoding into a character stream in Unicode is via 897 * the <code>InputStreamReader</code> and <code>BufferedReader</code> 898 * classes. 899 */ 900 @Deprecated 901 public InputStream getLocalizedInputStream(InputStream in) { 902 return in; 903 } 904 905 /** 906 * Creates a localized version of an output stream. This method 907 * takes an <code>OutputStream</code> and returns an 908 * <code>OutputStream</code> equivalent to the argument in all respects 909 * except that it is localized: as Unicode characters are written to 910 * the stream, they are automatically converted to the local 911 * character set. 912 * <p> 913 * If the argument is already a localized stream, it may be returned 914 * as the result. 915 * 916 * @deprecated As of JDK 1.1, the preferred way to translate a 917 * Unicode character stream into a byte stream in the local encoding is via 918 * the <code>OutputStreamWriter</code>, <code>BufferedWriter</code>, and 919 * <code>PrintWriter</code> classes. 920 * 921 * @param out OutputStream to localize 922 * @return a localized output stream 923 * @see java.io.OutputStream 924 * @see java.io.BufferedWriter#BufferedWriter(java.io.Writer) 925 * @see java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream) 926 * @see java.io.PrintWriter#PrintWriter(java.io.OutputStream) 927 */ 928 @Deprecated 929 public OutputStream getLocalizedOutputStream(OutputStream out) { 930 return out; 931 } 932 933 } | 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 26 package java.lang; 27 28 import java.io.*; 29 import java.util.StringTokenizer; 30 import sun.reflect.CallerSensitive; 31 import sun.reflect.Reflection; 32 33 /** 34 * Every Java application has a single instance of class 35 * {@code Runtime} that allows the application to interface with 36 * the environment in which the application is running. The current 37 * runtime can be obtained from the {@code getRuntime} method. 38 * <p> 39 * An application cannot create its own instance of this class. 40 * 41 * @author unascribed 42 * @see java.lang.Runtime#getRuntime() 43 * @since 1.0 44 */ 45 46 public class Runtime { 47 private static Runtime currentRuntime = new Runtime(); 48 49 /** 50 * Returns the runtime object associated with the current Java application. 51 * Most of the methods of class {@code Runtime} are instance 52 * methods and must be invoked with respect to the current runtime object. 53 * 54 * @return the {@code Runtime} object associated with the current 55 * Java application. 56 */ 57 public static Runtime getRuntime() { 58 return currentRuntime; 59 } 60 61 /** Don't let anyone else instantiate this class */ 62 private Runtime() {} 63 64 /** 65 * Terminates the currently running Java virtual machine by initiating its 66 * shutdown sequence. This method never returns normally. The argument 67 * serves as a status code; by convention, a nonzero status code indicates 68 * abnormal termination. 69 * 70 * <p> The virtual machine's shutdown sequence consists of two phases. In 71 * the first phase all registered {@link #addShutdownHook shutdown hooks}, 72 * if any, are started in some unspecified order and allowed to run 73 * concurrently until they finish. In the second phase all uninvoked 74 * finalizers are run if {@link #runFinalizersOnExit finalization-on-exit} 75 * has been enabled. Once this is done the virtual machine {@link #halt 76 * halts}. 77 * 78 * <p> If this method is invoked after the virtual machine has begun its 79 * shutdown sequence then if shutdown hooks are being run this method will 80 * block indefinitely. If shutdown hooks have already been run and on-exit 81 * finalization has been enabled then this method halts the virtual machine 82 * with the given status code if the status is nonzero; otherwise, it 83 * blocks indefinitely. 84 * 85 * <p> The {@link System#exit(int) System.exit} method is the 86 * conventional and convenient means of invoking this method. 87 * 88 * @param status 89 * Termination status. By convention, a nonzero status code 90 * indicates abnormal termination. 91 * 92 * @throws SecurityException 93 * If a security manager is present and its {@link 94 * SecurityManager#checkExit checkExit} method does not permit 95 * exiting with the specified status 96 * 97 * @see java.lang.SecurityException 98 * @see java.lang.SecurityManager#checkExit(int) 99 * @see #addShutdownHook 100 * @see #removeShutdownHook 101 * @see #runFinalizersOnExit 102 * @see #halt(int) 103 */ 104 public void exit(int status) { 105 SecurityManager security = System.getSecurityManager(); 106 if (security != null) { 107 security.checkExit(status); 108 } 109 Shutdown.exit(status); 110 } 111 112 /** 113 * Registers a new virtual-machine shutdown hook. 114 * 115 * <p> The Java virtual machine <i>shuts down</i> in response to two kinds 116 * of events: 117 * 118 * <ul> 119 * 120 * <li> The program <i>exits</i> normally, when the last non-daemon 121 * thread exits or when the {@link #exit exit} (equivalently, 122 * {@link System#exit(int) System.exit}) method is invoked, or 123 * 124 * <li> The virtual machine is <i>terminated</i> in response to a 125 * user interrupt, such as typing {@literal ^C}, or a system-wide event, 126 * such as user logoff or system shutdown. 127 * 128 * </ul> 129 * 130 * <p> A <i>shutdown hook</i> is simply an initialized but unstarted 131 * thread. When the virtual machine begins its shutdown sequence it will 132 * start all registered shutdown hooks in some unspecified order and let 133 * them run concurrently. When all the hooks have finished it will then 134 * run all uninvoked finalizers if finalization-on-exit has been enabled. 135 * Finally, the virtual machine will halt. Note that daemon threads will 136 * continue to run during the shutdown sequence, as will non-daemon threads 137 * if shutdown was initiated by invoking the {@link #exit exit} method. 138 * 139 * <p> Once the shutdown sequence has begun it can be stopped only by 140 * invoking the {@link #halt halt} method, which forcibly 141 * terminates the virtual machine. 142 * 143 * <p> Once the shutdown sequence has begun it is impossible to register a 144 * new shutdown hook or de-register a previously-registered hook. 145 * Attempting either of these operations will cause an 146 * {@link IllegalStateException} to be thrown. 147 * 148 * <p> Shutdown hooks run at a delicate time in the life cycle of a virtual 149 * machine and should therefore be coded defensively. They should, in 150 * particular, be written to be thread-safe and to avoid deadlocks insofar 151 * as possible. They should also not rely blindly upon services that may 152 * have registered their own shutdown hooks and therefore may themselves in 153 * the process of shutting down. Attempts to use other thread-based 154 * services such as the AWT event-dispatch thread, for example, may lead to 155 * deadlocks. 156 * 157 * <p> Shutdown hooks should also finish their work quickly. When a 158 * program invokes {@link #exit exit} the expectation is 159 * that the virtual machine will promptly shut down and exit. When the 160 * virtual machine is terminated due to user logoff or system shutdown the 161 * underlying operating system may only allow a fixed amount of time in 162 * which to shut down and exit. It is therefore inadvisable to attempt any 163 * user interaction or to perform a long-running computation in a shutdown 164 * hook. 165 * 166 * <p> Uncaught exceptions are handled in shutdown hooks just as in any 167 * other thread, by invoking the {@link ThreadGroup#uncaughtException 168 * uncaughtException} method of the thread's {@link 169 * ThreadGroup} object. The default implementation of this method 170 * prints the exception's stack trace to {@link System#err} and 171 * terminates the thread; it does not cause the virtual machine to exit or 172 * halt. 173 * 174 * <p> In rare circumstances the virtual machine may <i>abort</i>, that is, 175 * stop running without shutting down cleanly. This occurs when the 176 * virtual machine is terminated externally, for example with the 177 * {@code SIGKILL} signal on Unix or the {@code TerminateProcess} call on 178 * Microsoft Windows. The virtual machine may also abort if a native 179 * method goes awry by, for example, corrupting internal data structures or 180 * attempting to access nonexistent memory. If the virtual machine aborts 181 * then no guarantee can be made about whether or not any shutdown hooks 182 * will be run. 183 * 184 * @param hook 185 * An initialized but unstarted {@link Thread} object 186 * 187 * @throws IllegalArgumentException 188 * If the specified hook has already been registered, 189 * or if it can be determined that the hook is already running or 190 * has already been run 191 * 192 * @throws IllegalStateException 193 * If the virtual machine is already in the process 194 * of shutting down 195 * 196 * @throws SecurityException 197 * If a security manager is present and it denies 198 * {@link RuntimePermission}("shutdownHooks") 199 * 200 * @see #removeShutdownHook 201 * @see #halt(int) 202 * @see #exit(int) 203 * @since 1.3 204 */ 205 public void addShutdownHook(Thread hook) { 206 SecurityManager sm = System.getSecurityManager(); 207 if (sm != null) { 208 sm.checkPermission(new RuntimePermission("shutdownHooks")); 209 } 210 ApplicationShutdownHooks.add(hook); 211 } 212 213 /** 214 * De-registers a previously-registered virtual-machine shutdown hook. 215 * 216 * @param hook the hook to remove 217 * @return {@code true} if the specified hook had previously been 218 * registered and was successfully de-registered, {@code false} 219 * otherwise. 220 * 221 * @throws IllegalStateException 222 * If the virtual machine is already in the process of shutting 223 * down 224 * 225 * @throws SecurityException 226 * If a security manager is present and it denies 227 * {@link RuntimePermission}("shutdownHooks") 228 * 229 * @see #addShutdownHook 230 * @see #exit(int) 231 * @since 1.3 232 */ 233 public boolean removeShutdownHook(Thread hook) { 234 SecurityManager sm = System.getSecurityManager(); 235 if (sm != null) { 236 sm.checkPermission(new RuntimePermission("shutdownHooks")); 237 } 238 return ApplicationShutdownHooks.remove(hook); 239 } 240 241 /** 242 * Forcibly terminates the currently running Java virtual machine. This 243 * method never returns normally. 244 * 245 * <p> This method should be used with extreme caution. Unlike the 246 * {@link #exit exit} method, this method does not cause shutdown 247 * hooks to be started and does not run uninvoked finalizers if 248 * finalization-on-exit has been enabled. If the shutdown sequence has 249 * already been initiated then this method does not wait for any running 250 * shutdown hooks or finalizers to finish their work. 251 * 252 * @param status 253 * Termination status. By convention, a nonzero status code 254 * indicates abnormal termination. If the {@link Runtime#exit 255 * exit} (equivalently, {@link System#exit(int) 256 * System.exit}) method has already been invoked then this 257 * status code will override the status code passed to that method. 258 * 259 * @throws SecurityException 260 * If a security manager is present and its {@link 261 * SecurityManager#checkExit checkExit} method does not permit 262 * an exit with the specified status 263 * 264 * @see #exit 265 * @see #addShutdownHook 266 * @see #removeShutdownHook 267 * @since 1.3 268 */ 269 public void halt(int status) { 270 SecurityManager sm = System.getSecurityManager(); 271 if (sm != null) { 272 sm.checkExit(status); 273 } 274 Shutdown.halt(status); 275 } 276 277 /** 278 * Enable or disable finalization on exit; doing so specifies that the 279 * finalizers of all objects that have finalizers that have not yet been 280 * automatically invoked are to be run before the Java runtime exits. 281 * By default, finalization on exit is disabled. 282 * 283 * <p>If there is a security manager, 284 * its {@code checkExit} method is first called 285 * with 0 as its argument to ensure the exit is allowed. 286 * This could result in a SecurityException. 287 * 288 * @param value true to enable finalization on exit, false to disable 289 * @deprecated This method is inherently unsafe. It may result in 290 * finalizers being called on live objects while other threads are 291 * concurrently manipulating those objects, resulting in erratic 292 * behavior or deadlock. 293 * 294 * @throws SecurityException 295 * if a security manager exists and its {@code checkExit} 296 * method doesn't allow the exit. 297 * 298 * @see java.lang.Runtime#exit(int) 299 * @see java.lang.Runtime#gc() 300 * @see java.lang.SecurityManager#checkExit(int) 301 * @since 1.1 302 */ 303 @Deprecated 304 public static void runFinalizersOnExit(boolean value) { 305 SecurityManager security = System.getSecurityManager(); 306 if (security != null) { 307 try { 308 security.checkExit(0); 309 } catch (SecurityException e) { 310 throw new SecurityException("runFinalizersOnExit"); 311 } 312 } 313 Shutdown.setRunFinalizersOnExit(value); 314 } 315 316 /** 317 * Executes the specified string command in a separate process. 318 * 319 * <p>This is a convenience method. An invocation of the form 320 * {@code exec(command)} 321 * behaves in exactly the same way as the invocation 322 * {@link #exec(String, String[], File) exec}{@code (command, null, null)}. 323 * 324 * @param command a specified system command. 325 * 326 * @return A new {@link Process} object for managing the subprocess 327 * 328 * @throws SecurityException 329 * If a security manager exists and its 330 * {@link SecurityManager#checkExec checkExec} 331 * method doesn't allow creation of the subprocess 332 * 333 * @throws IOException 334 * If an I/O error occurs 335 * 336 * @throws NullPointerException 337 * If {@code command} is {@code null} 338 * 339 * @throws IllegalArgumentException 340 * If {@code command} is empty 341 * 342 * @see #exec(String[], String[], File) 343 * @see ProcessBuilder 344 */ 345 public Process exec(String command) throws IOException { 346 return exec(command, null, null); 347 } 348 349 /** 350 * Executes the specified string command in a separate process with the 351 * specified environment. 352 * 353 * <p>This is a convenience method. An invocation of the form 354 * {@code exec(command, envp)} 355 * behaves in exactly the same way as the invocation 356 * {@link #exec(String, String[], File) exec}{@code (command, envp, null)}. 357 * 358 * @param command a specified system command. 359 * 360 * @param envp array of strings, each element of which 361 * has environment variable settings in the format 362 * <i>name</i>=<i>value</i>, or 363 * {@code null} if the subprocess should inherit 364 * the environment of the current process. 365 * 366 * @return A new {@link Process} object for managing the subprocess 367 * 368 * @throws SecurityException 369 * If a security manager exists and its 370 * {@link SecurityManager#checkExec checkExec} 371 * method doesn't allow creation of the subprocess 372 * 373 * @throws IOException 374 * If an I/O error occurs 375 * 376 * @throws NullPointerException 377 * If {@code command} is {@code null}, 378 * or one of the elements of {@code envp} is {@code null} 379 * 380 * @throws IllegalArgumentException 381 * If {@code command} is empty 382 * 383 * @see #exec(String[], String[], File) 384 * @see ProcessBuilder 385 */ 386 public Process exec(String command, String[] envp) throws IOException { 387 return exec(command, envp, null); 388 } 389 390 /** 391 * Executes the specified string command in a separate process with the 392 * specified environment and working directory. 393 * 394 * <p>This is a convenience method. An invocation of the form 395 * {@code exec(command, envp, dir)} 396 * behaves in exactly the same way as the invocation 397 * {@link #exec(String[], String[], File) exec}{@code (cmdarray, envp, dir)}, 398 * where {@code cmdarray} is an array of all the tokens in 399 * {@code command}. 400 * 401 * <p>More precisely, the {@code command} string is broken 402 * into tokens using a {@link StringTokenizer} created by the call 403 * {@code new {@link StringTokenizer}(command)} with no 404 * further modification of the character categories. The tokens 405 * produced by the tokenizer are then placed in the new string 406 * array {@code cmdarray}, in the same order. 407 * 408 * @param command a specified system command. 409 * 410 * @param envp array of strings, each element of which 411 * has environment variable settings in the format 412 * <i>name</i>=<i>value</i>, or 413 * {@code null} if the subprocess should inherit 414 * the environment of the current process. 415 * 416 * @param dir the working directory of the subprocess, or 417 * {@code null} if the subprocess should inherit 418 * the working directory of the current process. 419 * 420 * @return A new {@link Process} object for managing the subprocess 421 * 422 * @throws SecurityException 423 * If a security manager exists and its 424 * {@link SecurityManager#checkExec checkExec} 425 * method doesn't allow creation of the subprocess 426 * 427 * @throws IOException 428 * If an I/O error occurs 429 * 430 * @throws NullPointerException 431 * If {@code command} is {@code null}, 432 * or one of the elements of {@code envp} is {@code null} 433 * 434 * @throws IllegalArgumentException 435 * If {@code command} is empty 436 * 437 * @see ProcessBuilder 438 * @since 1.3 439 */ 440 public Process exec(String command, String[] envp, File dir) 441 throws IOException { 442 if (command.length() == 0) 443 throw new IllegalArgumentException("Empty command"); 444 445 StringTokenizer st = new StringTokenizer(command); 446 String[] cmdarray = new String[st.countTokens()]; 447 for (int i = 0; st.hasMoreTokens(); i++) 448 cmdarray[i] = st.nextToken(); 449 return exec(cmdarray, envp, dir); 450 } 451 452 /** 453 * Executes the specified command and arguments in a separate process. 454 * 455 * <p>This is a convenience method. An invocation of the form 456 * {@code exec(cmdarray)} 457 * behaves in exactly the same way as the invocation 458 * {@link #exec(String[], String[], File) exec}{@code (cmdarray, null, null)}. 459 * 460 * @param cmdarray array containing the command to call and 461 * its arguments. 462 * 463 * @return A new {@link Process} object for managing the subprocess 464 * 465 * @throws SecurityException 466 * If a security manager exists and its 467 * {@link SecurityManager#checkExec checkExec} 468 * method doesn't allow creation of the subprocess 469 * 470 * @throws IOException 471 * If an I/O error occurs 472 * 473 * @throws NullPointerException 474 * If {@code cmdarray} is {@code null}, 475 * or one of the elements of {@code cmdarray} is {@code null} 476 * 477 * @throws IndexOutOfBoundsException 478 * If {@code cmdarray} is an empty array 479 * (has length {@code 0}) 480 * 481 * @see ProcessBuilder 482 */ 483 public Process exec(String cmdarray[]) throws IOException { 484 return exec(cmdarray, null, null); 485 } 486 487 /** 488 * Executes the specified command and arguments in a separate process 489 * with the specified environment. 490 * 491 * <p>This is a convenience method. An invocation of the form 492 * {@code exec(cmdarray, envp)} 493 * behaves in exactly the same way as the invocation 494 * {@link #exec(String[], String[], File) exec}{@code (cmdarray, envp, null)}. 495 * 496 * @param cmdarray array containing the command to call and 497 * its arguments. 498 * 499 * @param envp array of strings, each element of which 500 * has environment variable settings in the format 501 * <i>name</i>=<i>value</i>, or 502 * {@code null} if the subprocess should inherit 503 * the environment of the current process. 504 * 505 * @return A new {@link Process} object for managing the subprocess 506 * 507 * @throws SecurityException 508 * If a security manager exists and its 509 * {@link SecurityManager#checkExec checkExec} 510 * method doesn't allow creation of the subprocess 511 * 512 * @throws IOException 513 * If an I/O error occurs 514 * 515 * @throws NullPointerException 516 * If {@code cmdarray} is {@code null}, 517 * or one of the elements of {@code cmdarray} is {@code null}, 518 * or one of the elements of {@code envp} is {@code null} 519 * 520 * @throws IndexOutOfBoundsException 521 * If {@code cmdarray} is an empty array 522 * (has length {@code 0}) 523 * 524 * @see ProcessBuilder 525 */ 526 public Process exec(String[] cmdarray, String[] envp) throws IOException { 527 return exec(cmdarray, envp, null); 528 } 529 530 531 /** 532 * Executes the specified command and arguments in a separate process with 533 * the specified environment and working directory. 534 * 535 * <p>Given an array of strings {@code cmdarray}, representing the 536 * tokens of a command line, and an array of strings {@code envp}, 537 * representing "environment" variable settings, this method creates 538 * a new process in which to execute the specified command. 539 * 540 * <p>This method checks that {@code cmdarray} is a valid operating 541 * system command. Which commands are valid is system-dependent, 542 * but at the very least the command must be a non-empty list of 543 * non-null strings. 544 * 545 * <p>If {@code envp} is {@code null}, the subprocess inherits the 546 * environment settings of the current process. 547 * 548 * <p>A minimal set of system dependent environment variables may 549 * be required to start a process on some operating systems. 550 * As a result, the subprocess may inherit additional environment variable 551 * settings beyond those in the specified environment. 552 * 553 * <p>{@link ProcessBuilder#start()} is now the preferred way to 554 * start a process with a modified environment. 555 * 556 * <p>The working directory of the new subprocess is specified by {@code dir}. 557 * If {@code dir} is {@code null}, the subprocess inherits the 558 * current working directory of the current process. 559 * 560 * <p>If a security manager exists, its 561 * {@link SecurityManager#checkExec checkExec} 562 * method is invoked with the first component of the array 563 * {@code cmdarray} as its argument. This may result in a 564 * {@link SecurityException} being thrown. 565 * 566 * <p>Starting an operating system process is highly system-dependent. 567 * Among the many things that can go wrong are: 568 * <ul> 569 * <li>The operating system program file was not found. 570 * <li>Access to the program file was denied. 571 * <li>The working directory does not exist. 572 * </ul> 573 * 574 * <p>In such cases an exception will be thrown. The exact nature 575 * of the exception is system-dependent, but it will always be a 576 * subclass of {@link IOException}. 577 * 578 * <p>If the operating system does not support the creation of 579 * processes, an {@link UnsupportedOperationException} will be thrown. 580 * 581 * 582 * @param cmdarray array containing the command to call and 583 * its arguments. 584 * 585 * @param envp array of strings, each element of which 586 * has environment variable settings in the format 587 * <i>name</i>=<i>value</i>, or 588 * {@code null} if the subprocess should inherit 589 * the environment of the current process. 590 * 591 * @param dir the working directory of the subprocess, or 592 * {@code null} if the subprocess should inherit 593 * the working directory of the current process. 594 * 595 * @return A new {@link Process} object for managing the subprocess 596 * 597 * @throws SecurityException 598 * If a security manager exists and its 599 * {@link SecurityManager#checkExec checkExec} 600 * method doesn't allow creation of the subprocess 601 * 602 * @throws UnsupportedOperationException 603 * If the operating system does not support the creation of processes. 604 * 605 * @throws IOException 606 * If an I/O error occurs 607 * 608 * @throws NullPointerException 609 * If {@code cmdarray} is {@code null}, 610 * or one of the elements of {@code cmdarray} is {@code null}, 611 * or one of the elements of {@code envp} is {@code null} 612 * 613 * @throws IndexOutOfBoundsException 614 * If {@code cmdarray} is an empty array 615 * (has length {@code 0}) 616 * 617 * @see ProcessBuilder 618 * @since 1.3 619 */ 620 public Process exec(String[] cmdarray, String[] envp, File dir) 621 throws IOException { 622 return new ProcessBuilder(cmdarray) 623 .environment(envp) 624 .directory(dir) 625 .start(); 626 } 627 628 /** 629 * Returns the number of processors available to the Java virtual machine. 630 * 631 * <p> This value may change during a particular invocation of the virtual 632 * machine. Applications that are sensitive to the number of available 633 * processors should therefore occasionally poll this property and adjust 634 * their resource usage appropriately. </p> 635 * 636 * @return the maximum number of processors available to the virtual 637 * machine; never smaller than one 638 * @since 1.4 639 */ 640 public native int availableProcessors(); 641 642 /** 643 * Returns the amount of free memory in the Java Virtual Machine. 644 * Calling the 645 * {@code gc} method may result in increasing the value returned 646 * by {@code freeMemory.} 647 * 648 * @return an approximation to the total amount of memory currently 649 * available for future allocated objects, measured in bytes. 650 */ 651 public native long freeMemory(); 652 653 /** 654 * Returns the total amount of memory in the Java virtual machine. 655 * The value returned by this method may vary over time, depending on 656 * the host environment. 657 * <p> 658 * Note that the amount of memory required to hold an object of any 659 * given type may be implementation-dependent. 660 * 661 * @return the total amount of memory currently available for current 662 * and future objects, measured in bytes. 663 */ 664 public native long totalMemory(); 665 666 /** 667 * Returns the maximum amount of memory that the Java virtual machine will 668 * attempt to use. If there is no inherent limit then the value {@link 669 * java.lang.Long#MAX_VALUE} will be returned. 670 * 671 * @return the maximum amount of memory that the virtual machine will 672 * attempt to use, measured in bytes 673 * @since 1.4 674 */ 675 public native long maxMemory(); 676 677 /** 678 * Runs the garbage collector. 679 * Calling this method suggests that the Java virtual machine expend 680 * effort toward recycling unused objects in order to make the memory 681 * they currently occupy available for quick reuse. When control 682 * returns from the method call, the virtual machine has made 683 * its best effort to recycle all discarded objects. 684 * <p> 685 * The name {@code gc} stands for "garbage 686 * collector". The virtual machine performs this recycling 687 * process automatically as needed, in a separate thread, even if the 688 * {@code gc} method is not invoked explicitly. 689 * <p> 690 * The method {@link System#gc()} is the conventional and convenient 691 * means of invoking this method. 692 */ 693 public native void gc(); 694 695 /* Wormhole for calling java.lang.ref.Finalizer.runFinalization */ 696 private static native void runFinalization0(); 697 698 /** 699 * Runs the finalization methods of any objects pending finalization. 700 * Calling this method suggests that the Java virtual machine expend 701 * effort toward running the {@code finalize} methods of objects 702 * that have been found to be discarded but whose {@code finalize} 703 * methods have not yet been run. When control returns from the 704 * method call, the virtual machine has made a best effort to 705 * complete all outstanding finalizations. 706 * <p> 707 * The virtual machine performs the finalization process 708 * automatically as needed, in a separate thread, if the 709 * {@code runFinalization} method is not invoked explicitly. 710 * <p> 711 * The method {@link System#runFinalization()} is the conventional 712 * and convenient means of invoking this method. 713 * 714 * @see java.lang.Object#finalize() 715 */ 716 public void runFinalization() { 717 runFinalization0(); 718 } 719 720 /** 721 * Enables/Disables tracing of instructions. 722 * If the {@code boolean} argument is {@code true}, this 723 * method suggests that the Java virtual machine emit debugging 724 * information for each instruction in the virtual machine as it 725 * is executed. The format of this information, and the file or other 726 * output stream to which it is emitted, depends on the host environment. 727 * The virtual machine may ignore this request if it does not support 728 * this feature. The destination of the trace output is system 729 * dependent. 730 * <p> 731 * If the {@code boolean} argument is {@code false}, this 732 * method causes the virtual machine to stop performing the 733 * detailed instruction trace it is performing. 734 * 735 * @param on {@code true} to enable instruction tracing; 736 * {@code false} to disable this feature. 737 */ 738 public void traceInstructions(boolean on) { } 739 740 /** 741 * Enables/Disables tracing of method calls. 742 * If the {@code boolean} argument is {@code true}, this 743 * method suggests that the Java virtual machine emit debugging 744 * information for each method in the virtual machine as it is 745 * called. The format of this information, and the file or other output 746 * stream to which it is emitted, depends on the host environment. The 747 * virtual machine may ignore this request if it does not support 748 * this feature. 749 * <p> 750 * Calling this method with argument false suggests that the 751 * virtual machine cease emitting per-call debugging information. 752 * 753 * @param on {@code true} to enable instruction tracing; 754 * {@code false} to disable this feature. 755 */ 756 public void traceMethodCalls(boolean on) { } 757 758 /** 759 * Loads the native library specified by the filename argument. The filename 760 * argument must be an absolute path name. 761 * (for example 762 * {@code Runtime.getRuntime().load("/home/avh/lib/libX11.so");}). 763 * 764 * If the filename argument, when stripped of any platform-specific library 765 * prefix, path, and file extension, indicates a library whose name is, 766 * for example, L, and a native library called L is statically linked 767 * with the VM, then the JNI_OnLoad_L function exported by the library 768 * is invoked rather than attempting to load a dynamic library. 769 * A filename matching the argument does not have to exist in the file 770 * system. See the JNI Specification for more details. 771 * 772 * Otherwise, the filename argument is mapped to a native library image in 773 * an implementation-dependent manner. 774 * <p> 775 * First, if there is a security manager, its {@code checkLink} 776 * method is called with the {@code filename} as its argument. 777 * This may result in a security exception. 778 * <p> 779 * This is similar to the method {@link #loadLibrary(String)}, but it 780 * accepts a general file name as an argument rather than just a library 781 * name, allowing any file of native code to be loaded. 782 * <p> 783 * The method {@link System#load(String)} is the conventional and 784 * convenient means of invoking this method. 785 * 786 * @param filename the file to load. 787 * @exception SecurityException if a security manager exists and its 788 * {@code checkLink} method doesn't allow 789 * loading of the specified dynamic library 790 * @exception UnsatisfiedLinkError if either the filename is not an 791 * absolute path name, the native library is not statically 792 * linked with the VM, or the library cannot be mapped to 793 * a native library image by the host system. 794 * @exception NullPointerException if {@code filename} is 795 * {@code null} 796 * @see java.lang.Runtime#getRuntime() 797 * @see java.lang.SecurityException 798 * @see java.lang.SecurityManager#checkLink(java.lang.String) 799 */ 800 @CallerSensitive 801 public void load(String filename) { 802 load0(Reflection.getCallerClass(), filename); 803 } 804 805 synchronized void load0(Class<?> fromClass, String filename) { 806 SecurityManager security = System.getSecurityManager(); 807 if (security != null) { 808 security.checkLink(filename); 809 } 810 if (!(new File(filename).isAbsolute())) { 811 throw new UnsatisfiedLinkError( 812 "Expecting an absolute path of the library: " + filename); 813 } 814 ClassLoader.loadLibrary(fromClass, filename, true); 815 } 816 817 /** 818 * Loads the native library specified by the {@code libname} 819 * argument. The {@code libname} argument must not contain any platform 820 * specific prefix, file extension or path. If a native library 821 * called {@code libname} is statically linked with the VM, then the 822 * JNI_OnLoad_{@code libname} function exported by the library is invoked. 823 * See the JNI Specification for more details. 824 * 825 * Otherwise, the libname argument is loaded from a system library 826 * location and mapped to a native library image in an implementation- 827 * dependent manner. 828 * <p> 829 * First, if there is a security manager, its {@code checkLink} 830 * method is called with the {@code libname} as its argument. 831 * This may result in a security exception. 832 * <p> 833 * The method {@link System#loadLibrary(String)} is the conventional 834 * and convenient means of invoking this method. If native 835 * methods are to be used in the implementation of a class, a standard 836 * strategy is to put the native code in a library file (call it 837 * {@code LibFile}) and then to put a static initializer: 838 * <blockquote><pre> 839 * static { System.loadLibrary("LibFile"); } 840 * </pre></blockquote> 841 * within the class declaration. When the class is loaded and 842 * initialized, the necessary native code implementation for the native 843 * methods will then be loaded as well. 844 * <p> 845 * If this method is called more than once with the same library 846 * name, the second and subsequent calls are ignored. 847 * 848 * @param libname the name of the library. 849 * @exception SecurityException if a security manager exists and its 850 * {@code checkLink} method doesn't allow 851 * loading of the specified dynamic library 852 * @exception UnsatisfiedLinkError if either the libname argument 853 * contains a file path, the native library is not statically 854 * linked with the VM, or the library cannot be mapped to a 855 * native library image by the host system. 856 * @exception NullPointerException if {@code libname} is 857 * {@code null} 858 * @see java.lang.SecurityException 859 * @see java.lang.SecurityManager#checkLink(java.lang.String) 860 */ 861 @CallerSensitive 862 public void loadLibrary(String libname) { 863 loadLibrary0(Reflection.getCallerClass(), libname); 864 } 865 866 synchronized void loadLibrary0(Class<?> fromClass, String libname) { 867 SecurityManager security = System.getSecurityManager(); 868 if (security != null) { 869 security.checkLink(libname); 870 } 871 if (libname.indexOf((int)File.separatorChar) != -1) { 872 throw new UnsatisfiedLinkError( 873 "Directory separator should not appear in library name: " + libname); 874 } 875 ClassLoader.loadLibrary(fromClass, libname, false); 876 } 877 878 /** 879 * Creates a localized version of an input stream. This method takes 880 * an {@code InputStream} and returns an {@code InputStream} 881 * equivalent to the argument in all respects except that it is 882 * localized: as characters in the local character set are read from 883 * the stream, they are automatically converted from the local 884 * character set to Unicode. 885 * <p> 886 * If the argument is already a localized stream, it may be returned 887 * as the result. 888 * 889 * @param in InputStream to localize 890 * @return a localized input stream 891 * @see java.io.InputStream 892 * @see java.io.BufferedReader#BufferedReader(java.io.Reader) 893 * @see java.io.InputStreamReader#InputStreamReader(java.io.InputStream) 894 * @deprecated As of JDK 1.1, the preferred way to translate a byte 895 * stream in the local encoding into a character stream in Unicode is via 896 * the {@code InputStreamReader} and {@code BufferedReader} 897 * classes. 898 */ 899 @Deprecated 900 public InputStream getLocalizedInputStream(InputStream in) { 901 return in; 902 } 903 904 /** 905 * Creates a localized version of an output stream. This method 906 * takes an {@code OutputStream} and returns an 907 * {@code OutputStream} equivalent to the argument in all respects 908 * except that it is localized: as Unicode characters are written to 909 * the stream, they are automatically converted to the local 910 * character set. 911 * <p> 912 * If the argument is already a localized stream, it may be returned 913 * as the result. 914 * 915 * @deprecated As of JDK 1.1, the preferred way to translate a 916 * Unicode character stream into a byte stream in the local encoding is via 917 * the {@code OutputStreamWriter}, {@code BufferedWriter}, and 918 * {@code PrintWriter} classes. 919 * 920 * @param out OutputStream to localize 921 * @return a localized output stream 922 * @see java.io.OutputStream 923 * @see java.io.BufferedWriter#BufferedWriter(java.io.Writer) 924 * @see java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream) 925 * @see java.io.PrintWriter#PrintWriter(java.io.OutputStream) 926 */ 927 @Deprecated 928 public OutputStream getLocalizedOutputStream(OutputStream out) { 929 return out; 930 } 931 932 } |