home *** CD-ROM | disk | FTP | other *** search
/ Apple Developer Connection Student Program / ADC Tools Sampler CD Disk 3 1999.iso / Metrowerks CodeWarrior / Java Support / Java_Source / Java2 / src / java / lang / Runtime.java < prev    next >
Encoding:
Java Source  |  1999-05-28  |  21.7 KB  |  525 lines  |  [TEXT/CWIE]

  1. /*
  2.  * @(#)Runtime.java    1.47 98/10/17
  3.  *
  4.  * Copyright 1995-1998 by Sun Microsystems, Inc.,
  5.  * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
  6.  * All rights reserved.
  7.  *
  8.  * This software is the confidential and proprietary information
  9.  * of Sun Microsystems, Inc. ("Confidential Information").  You
  10.  * shall not disclose such Confidential Information and shall use
  11.  * it only in accordance with the terms of the license agreement
  12.  * you entered into with Sun.
  13.  */
  14.  
  15. package java.lang;
  16.  
  17. import java.io.*;
  18. import java.util.StringTokenizer;
  19.  
  20. /**
  21.  * Every Java application has a single instance of class 
  22.  * <code>Runtime</code> that allows the application to interface with 
  23.  * the environment in which the application is running. The current 
  24.  * runtime can be obtained from the <code>getRuntime</code> method. 
  25.  * <p>
  26.  * An application cannot create its own instance of this class. 
  27.  *
  28.  * @author  unascribed
  29.  * @version 1.47, 10/17/98
  30.  * @see     java.lang.Runtime#getRuntime()
  31.  * @since   JDK1.0
  32.  */
  33.  
  34. public class Runtime {
  35.     private static Runtime currentRuntime = new Runtime();
  36.       
  37.     /**
  38.      * Returns the runtime object associated with the current Java application.
  39.      * Most of the methods of class <code>Runtime</code> are instance 
  40.      * methods and must be invoked with respect to the current runtime object. 
  41.      * 
  42.      * @return  the <code>Runtime</code> object associated with the current
  43.      *          Java application.
  44.      */
  45.     public static Runtime getRuntime() { 
  46.     return currentRuntime;
  47.     }
  48.     
  49.     /** Don't let anyone else instantiate this class */
  50.     private Runtime() {}
  51.  
  52.     /* Helper for exit
  53.      */
  54.     private native void exitInternal(int status);
  55.  
  56.     /**
  57.      * Terminates the currently running Java Virtual Machine. This 
  58.      * method never returns normally. 
  59.      * <p>
  60.      * First, if there is a security manager, its <code>checkExit</code> 
  61.      * method is called with the status as its argument. This may result 
  62.      * in a security exception. 
  63.      * <p>
  64.      * The argument serves as a status code; by convention, a nonzero 
  65.      * status code indicates abnormal termination. 
  66.      * <p>
  67.      * The method {@link System#exit(int)} is the conventional and 
  68.      * convenient means of invoking this method.
  69.      *
  70.      * @param      status   exit status. By convention, a nonzero status 
  71.      *             code indicates abnormal termination.
  72.      * @throws  SecurityException
  73.      *        if a security manager exists and its <code>checkExit</code> 
  74.      *        method doesn't allow exit with the specified status.
  75.      * @see        java.lang.SecurityException
  76.      * @see        java.lang.SecurityManager#checkExit(int)
  77.      */
  78.     public void exit(int status) {
  79.     SecurityManager security = System.getSecurityManager();
  80.     if (security != null) {
  81.         security.checkExit(status);
  82.     }
  83.     exitInternal(status);
  84.     }
  85.  
  86.     /* Wormhole for calling java.lang.ref.Finalizer.setRunFinalizersOnExit */
  87.     private static native void runFinalizersOnExit0(boolean value);
  88.  
  89.     /**
  90.      * Enable or disable finalization on exit; doing so specifies that the
  91.      * finalizers of all objects that have finalizers that have not yet been
  92.      * automatically invoked are to be run before the Java runtime exits.
  93.      * By default, finalization on exit is disabled.
  94.      * 
  95.      * <p>If there is a security manager, 
  96.      * its <code>checkExit</code> method is first called
  97.      * with 0 as its argument to ensure the exit is allowed. 
  98.      * This could result in a SecurityException.
  99.      *
  100.      * @deprecated  This method is inherently unsafe.  It may result in
  101.      *         finalizers being called on live objects while other threads are
  102.      *      concurrently manipulating those objects, resulting in erratic
  103.      *        behavior or deadlock.
  104.      * 
  105.      * @throws  SecurityException
  106.      *        if a security manager exists and its <code>checkExit</code> 
  107.      *        method doesn't allow the exit.
  108.      *
  109.      * @see     java.lang.Runtime#exit(int)
  110.      * @see     java.lang.Runtime#gc()
  111.      * @see     java.lang.SecurityManager#checkExit(int)
  112.      * @since   JDK1.1
  113.      */
  114.     public static void runFinalizersOnExit(boolean value) {
  115.     SecurityManager security = System.getSecurityManager();
  116.     if (security != null) {
  117.         try {
  118.         security.checkExit(0); 
  119.         } catch (SecurityException e) {
  120.         throw new SecurityException("runFinalizersOnExit");
  121.         }
  122.     }
  123.     runFinalizersOnExit0(value);
  124.     }
  125.  
  126.     /* Helper for exec
  127.      */
  128.     private native Process execInternal(String cmdarray[], String envp[]) 
  129.      throws IOException;
  130.  
  131.     /**
  132.      * Executes the specified string command in a separate process. 
  133.      * <p>
  134.      * The <code>command</code> argument is parsed into tokens and then 
  135.      * executed as a command in a separate process. The token parsing is 
  136.      * done by a {@link java.util.StringTokenizer} created by the call:
  137.      * <blockquote><pre>
  138.      * new StringTokenizer(command)
  139.      * </pre></blockquote> 
  140.      * with no further modifications of the character categories. 
  141.      * This method has exactly the same effect as 
  142.      * <code>exec(command, null)</code>. 
  143.      *
  144.      * @param      command   a specified system command.
  145.      * @return     a <code>Process</code> object for managing the subprocess.
  146.      * @exception  SecurityException  if a security manager exists and its  
  147.      *             <code>checkExec</code> method doesn't allow creation of a subprocess.
  148.      * @see        java.lang.Runtime#exec(java.lang.String, java.lang.String[])
  149.      * @see     java.lang.SecurityManager#checkExec(java.lang.String)
  150.      */
  151.     public Process exec(String command) throws IOException {
  152.     return exec(command, null);
  153.     }
  154.  
  155.     /**
  156.      * Executes the specified string command in a separate process with the 
  157.      * specified environment. 
  158.      * <p>
  159.      * This method breaks the <code>command</code> string into tokens and 
  160.      * creates a new array <code>cmdarray</code> containing the tokens in the 
  161.      * order that they were produced by the string tokenizer; it 
  162.      * then performs the call <code>exec(cmdarray, envp)</code>. The token
  163.      * parsing is done by a {@link java.util.StringTokenizer} created by 
  164.      * the call: 
  165.      * <blockquote><pre>
  166.      * new StringTokenizer(command)
  167.      * </pre></blockquote>
  168.      * with no further modification of the character categories. 
  169.      *
  170.      * @param      command   a specified system command.
  171.      * @param      envp      array of strings, each element of which 
  172.      *                       has environment variable settings in format
  173.      *                       <i>name</i>=<i>value</i>.
  174.      * @return     a <code>Process</code> object for managing the subprocess.
  175.      * @exception  SecurityException  if a security manager exists and its  
  176.      *             <code>checkExec</code> method doesn't allow creation of a subprocess.
  177.      * @see        java.lang.Runtime#exec(java.lang.String[])
  178.      * @see        java.lang.Runtime#exec(java.lang.String[], java.lang.String[])
  179.      * @see        java.lang.SecurityManager#checkExec(java.lang.String)
  180.      */
  181.     public Process exec(String command, String envp[]) throws IOException {
  182.     int count = 0;
  183.     String cmdarray[];
  184.      StringTokenizer st;
  185.  
  186.     st = new StringTokenizer(command);
  187.      count = st.countTokens();
  188.  
  189.     cmdarray = new String[count];
  190.     st = new StringTokenizer(command);
  191.     count = 0;
  192.      while (st.hasMoreTokens()) {
  193.          cmdarray[count++] = st.nextToken();
  194.      }
  195.     return exec(cmdarray, envp);
  196.     }
  197.  
  198.     /**
  199.      * Executes the specified command and arguments in a separate process.
  200.      * <p>
  201.      * The command specified by the tokens in <code>cmdarray</code> is 
  202.      * executed as a command in a separate process. This has exactly the 
  203.      * same effect as <code>exec(cmdarray, null)</code>. 
  204.      * <p>
  205.      * If there is a security manager, its <code>checkExec</code> 
  206.      * method is called with the first component of the array 
  207.      * <code>cmdarray</code> as its argument. This may result in a security 
  208.      * exception. 
  209.      *
  210.      * @param      cmdarray   array containing the command to call and
  211.      *                        its arguments.
  212.      * @return     a <code>Process</code> object for managing the subprocess.
  213.      * @exception  SecurityException  if a security manager exists and its  
  214.      *             <code>checkExec</code> method doesn't allow creation of a subprocess.
  215.      * @see        java.lang.Runtime#exec(java.lang.String[], java.lang.String[])
  216.      * @see        java.lang.SecurityManager#checkExec(java.lang.String)
  217.      */
  218.     public Process exec(String cmdarray[]) throws IOException {
  219.     return exec(cmdarray, null);
  220.     }
  221.  
  222.     /**
  223.      * Executes the specified command and arguments in a separate process
  224.      * with the specified environment. 
  225.      * <p>
  226.      * If there is a security manager, its <code>checkExec</code> 
  227.      * method is called with the first component of the array 
  228.      * <code>cmdarray</code> as its argument. This may result in a security 
  229.      * exception. 
  230.      * <p>
  231.      * Given an array of strings <code>cmdarray</code>, representing the 
  232.      * tokens of a command line, and an array of strings <code>envp</code>, 
  233.      * representing "environment" variable settings, this method creates 
  234.      * a new process in which to execute the specified command. 
  235.      *
  236.      * @param      cmdarray   array containing the command to call and
  237.      *                        its arguments.
  238.      * @param      envp       array of strings, each element of which 
  239.      *                        has environment variable settings in format
  240.      *                        <i>name</i>=<i>value</i>.
  241.      * @return     a <code>Process</code> object for managing the subprocess.
  242.      * @exception  SecurityException  if a security manager exists and its  
  243.      *             <code>checkExec</code> method doesn't allow creation of a subprocess.
  244.      * @exception  NullPointerException if <code>cmdarray</code> is 
  245.      *             <code>null</code>.
  246.      * @exception  IndexOutOfBoundsException if <code>cmdarray</code> is an 
  247.      *             empty array (has length <code>0</code>).
  248.      * @see     java.lang.Process
  249.      * @see     java.lang.SecurityException
  250.      * @see     java.lang.SecurityManager#checkExec(java.lang.String)
  251.      */
  252.     public Process exec(String cmdarray[], String envp[]) throws IOException {
  253.         if (cmdarray.length == 0) {
  254.             throw new IndexOutOfBoundsException();            
  255.         }
  256.         for (int i = 0; i < cmdarray.length; i++) {
  257.             if (cmdarray[i] == null) {
  258.                 throw new NullPointerException();
  259.             }
  260.         }
  261.         if (envp != null) {
  262.             for (int i = 0; i < envp.length; i++) {
  263.                 if (envp[i] == null) {
  264.                     throw new NullPointerException();
  265.                 }
  266.             }
  267.         }
  268.     SecurityManager security = System.getSecurityManager();
  269.     if (security != null) {
  270.         security.checkExec(cmdarray[0]);
  271.     }
  272.     return execInternal(cmdarray, envp);
  273.     }
  274.  
  275.     /**
  276.      * Returns the amount of free memory in the system. Calling the 
  277.      * <code>gc</code> method may result in increasing the value returned 
  278.      * by <code>freeMemory.</code>
  279.      *
  280.      * @return  an approximation to the total amount of memory currently
  281.      *          available for future allocated objects, measured in bytes.
  282.      */
  283.     public native long freeMemory();
  284.  
  285.     /**
  286.      * Returns the total amount of memory in the Java Virtual Machine. 
  287.      * The value returned by this method may vary over time, depending on 
  288.      * the host environment.
  289.      * <p>
  290.      * Note that the amount of memory required to hold an object of any 
  291.      * given type may be implementation-dependent.
  292.      * 
  293.      * @return  the total amount of memory currently available for current 
  294.      *          and future objects, measured in bytes.
  295.      */
  296.     public native long totalMemory();
  297.  
  298.     /**
  299.      * Runs the garbage collector.
  300.      * Calling this method suggests that the Java Virtual Machine expend 
  301.      * effort toward recycling unused objects in order to make the memory 
  302.      * they currently occupy available for quick reuse. When control 
  303.      * returns from the method call, the Java Virtual Machine has made 
  304.      * its best effort to recycle all discarded objects. 
  305.      * <p>
  306.      * The name <code>gc</code> stands for "garbage 
  307.      * collector". The Java Virtual Machine performs this recycling 
  308.      * process automatically as needed, in a separate thread, even if the 
  309.      * <code>gc</code> method is not invoked explicitly.
  310.      * <p>
  311.      * The method {@link System#gc()} is hte conventional and convenient 
  312.      * means of invoking this method. 
  313.      */
  314.     public native void gc();
  315.  
  316.     /* Wormhole for calling java.lang.ref.Finalizer.runFinalization */
  317.     private static native void runFinalization0();
  318.  
  319.     /**
  320.      * Runs the finalization methods of any objects pending finalization.
  321.      * Calling this method suggests that the Java Virtual Machine expend 
  322.      * effort toward running the <code>finalize</code> methods of objects 
  323.      * that have been found to be discarded but whose <code>finalize</code> 
  324.      * methods have not yet been run. When control returns from the 
  325.      * method call, the Java Virtual Machine has made a best effort to 
  326.      * complete all outstanding finalizations. 
  327.      * <p>
  328.      * The Java Virtual Machine performs the finalization process 
  329.      * automatically as needed, in a separate thread, if the 
  330.      * <code>runFinalization</code> method is not invoked explicitly. 
  331.      * <p>
  332.      * The method {@link System#runFinalization()} is the conventional 
  333.      * and convenient means of invoking this method.
  334.      *
  335.      * @see     java.lang.Object#finalize()
  336.      */
  337.     public void runFinalization() {
  338.     runFinalization0();
  339.     }
  340.  
  341.     /**
  342.      * Enables/Disables tracing of instructions.
  343.      * If the <code>boolean</code> argument is <code>true</code>, this 
  344.      * method suggests that the Java Virtual Machine emit debugging 
  345.      * information for each instruction in the Java Virtual Machine as it 
  346.      * is executed. The format of this information, and the file or other 
  347.      * output stream to which it is emitted, depends on the host environment. 
  348.      * The virtual machine may ignore this request if it does not support 
  349.      * this feature. The destination of the trace output is system 
  350.      * dependent. 
  351.      * <p>
  352.      * If the <code>boolean</code> argument is <code>false</code>, this 
  353.      * method causes the Java Virtual Machine to stop performing the 
  354.      * detailed instruction trace it is performing.
  355.      *
  356.      * @param   on   <code>true</code> to enable instruction tracing;
  357.      *               <code>false</code> to disable this feature.
  358.      */
  359.     public native void traceInstructions(boolean on);
  360.  
  361.     /**
  362.      * Enables/Disables tracing of method calls.
  363.      * If the <code>boolean</code> argument is <code>true</code>, this 
  364.      * method suggests that the Java Virtual Machine emit debugging 
  365.      * information for each method in the Java Virtual Machine as it is 
  366.      * called. The format of this information, and the file or other output 
  367.      * stream to which it is emitted, depends on the host environment. The 
  368.      * virtual machine may ignore this request if it does not support 
  369.      * this feature.  
  370.      * <p>
  371.      * Calling this method with argument false suggests that the Java 
  372.      * Virtual Machine cease emitting per-call debugging information.
  373.      *
  374.      * @param   on   <code>true</code> to enable instruction tracing;
  375.      *               <code>false</code> to disable this feature.
  376.      */
  377.     public native void traceMethodCalls(boolean on);
  378.  
  379.     /**
  380.      * Loads the specified filename as a dynamic library. The filename 
  381.      * argument must be a complete pathname. 
  382.      * From <code>java_g</code> it will automagically insert "_g" before the
  383.      * ".so" (for example
  384.      * <code>Runtime.getRuntime().load("/home/avh/lib/libX11.so");</code>).
  385.      * <p>
  386.      * First, if there is a security manager, its <code>checkLink</code> 
  387.      * method is called with the <code>filename</code> as its argument. 
  388.      * This may result in a security exception. 
  389.      * <p>
  390.      * This is similar to the method {@link #loadLibrary(String)}, but it 
  391.      * accepts a general file name as an argument rathan than just a library 
  392.      * name, allowing any file of native code to be loaded.
  393.      * <p>
  394.      * The method {@link System#load(String)} is the conventional and 
  395.      * convenient means of invoking this method.
  396.      *
  397.      * @param      filename   the file to load.
  398.      * @exception  SecurityException  if a security manager exists and its  
  399.      *             <code>checkLink</code> method doesn't allow 
  400.      *             loading of the specified dynamic library
  401.      * @exception  UnsatisfiedLinkError  if the file does not exist.
  402.      * @see        java.lang.Runtime#getRuntime()
  403.      * @see        java.lang.SecurityException
  404.      * @see        java.lang.SecurityManager#checkLink(java.lang.String)
  405.      */
  406.     public void load(String filename) {
  407.         load0(System.getCallerClass(), filename);
  408.     }
  409.  
  410.     synchronized void load0(Class fromClass, String filename) {
  411.     SecurityManager security = System.getSecurityManager();
  412.     if (security != null) {
  413.         security.checkLink(filename);
  414.     }
  415.     if (!(new File(filename).isAbsolute())) {
  416.         throw new UnsatisfiedLinkError(
  417.             "Expecting an absolute path of the library: " + filename);
  418.     }
  419.     ClassLoader.loadLibrary(fromClass, filename, true);
  420.     }
  421.  
  422.     /**
  423.      * Loads the dynamic library with the specified library name. 
  424.      * A file containing native code is loaded from the local file system 
  425.      * from a place where library files are conventionally obtained. The 
  426.      * details of this process are implementation-dependent. The 
  427.      * mapping from a library name to a specific filename is done in a 
  428.      * system-specific manner. 
  429.      * <p>
  430.      * First, if there is a security manager, its <code>checkLink</code> 
  431.      * method is called with the <code>libname</code> as its argument. 
  432.      * This may result in a security exception. 
  433.      * <p>
  434.      * The method {@link System#loadLibrary(String)} is the conventional 
  435.      * and convenient means of invoking this method. If native
  436.      * methods are to be used in the implementation of a class, a standard 
  437.      * strategy is to put the native code in a library file (call it 
  438.      * <code>LibFile</code>) and then to put a static initializer:
  439.      * <blockquote><pre>
  440.      * static { System.loadLibrary("LibFile"); }
  441.      * </pre></blockquote>
  442.      * within the class declaration. When the class is loaded and 
  443.      * initialized, the necessary native code implementation for the native 
  444.      * methods will then be loaded as well. 
  445.      * <p>
  446.      * If this method is called more than once with the same library 
  447.      * name, the second and subsequent calls are ignored. 
  448.      *
  449.      * @param      libname   the name of the library.
  450.      * @exception  SecurityException  if a security manager exists and its  
  451.      *             <code>checkLink</code> method doesn't allow 
  452.      *             loading of the specified dynamic library
  453.      * @exception  UnsatisfiedLinkError  if the library does not exist.
  454.      * @see        java.lang.SecurityException
  455.      * @see        java.lang.SecurityManager#checkLink(java.lang.String)
  456.      */
  457.     public void loadLibrary(String libname) {
  458.         loadLibrary0(System.getCallerClass(), libname); 
  459.     }
  460.  
  461.     synchronized void loadLibrary0(Class fromClass, String libname) {
  462.     SecurityManager security = System.getSecurityManager();
  463.     if (security != null) {
  464.         security.checkLink(libname);
  465.     }
  466.     if (libname.indexOf((int)File.separatorChar) != -1) {
  467.         throw new UnsatisfiedLinkError(
  468.     "Directory separator should not appear in library name: " + libname);
  469.     }
  470.     ClassLoader.loadLibrary(fromClass, libname, false);
  471.     }
  472.  
  473.     /**
  474.      * Creates a localized version of an input stream. This method takes 
  475.      * an <code>InputStream</code> and returns an <code>InputStream</code> 
  476.      * equivalent to the argument in all respects except that it is 
  477.      * localized: as characters in the local character set are read from 
  478.      * the stream, they are automatically converted from the local 
  479.      * character set to Unicode. 
  480.      * <p>
  481.      * If the argument is already a localized stream, it may be returned 
  482.      * as the result. 
  483.      *
  484.      * @deprecated As of JDK 1.1, the preferred way translate a byte
  485.      * stream in the local encoding into a character stream in Unicode is via
  486.      * the <code>InputStreamReader</code> and <code>BufferedReader</code>
  487.      * classes.
  488.      *
  489.      * @return     a localized input stream.
  490.      * @see        java.io.InputStream
  491.      * @see        java.io.BufferedReader#BufferedReader(java.io.Reader)
  492.      * @see        java.io.InputStreamReader#InputStreamReader(java.io.InputStream)
  493.      */
  494.     public InputStream getLocalizedInputStream(InputStream in) {
  495.     return in;
  496.     }
  497.  
  498.     /**
  499.      * Creates a localized version of an output stream. This method 
  500.      * takes an <code>OutputStream</code> and returns an 
  501.      * <code>OutputStream</code> equivalent to the argument in all respects 
  502.      * except that it is localized: as Unicode characters are written to 
  503.      * the stream, they are automatically converted to the local 
  504.      * character set. 
  505.      * <p>
  506.      * If the argument is already a localized stream, it may be returned 
  507.      * as the result. 
  508.      *
  509.      * @deprecated As of JDK 1.1, the preferred way to translate a
  510.      * Unicode character stream into a byte stream in the local encoding is via
  511.      * the <code>OutputStreamWriter</code>, <code>BufferedWriter</code>, and
  512.      * <code>PrintWriter</code> classes.
  513.      *
  514.      * @return     a localized output stream.
  515.      * @see        java.io.OutputStream
  516.      * @see        java.io.BufferedWriter#BufferedWriter(java.io.Writer)
  517.      * @see        java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
  518.      * @see        java.io.PrintWriter#PrintWriter(java.io.OutputStream)
  519.      */
  520.     public OutputStream getLocalizedOutputStream(OutputStream out) {
  521.     return out;
  522.     }
  523.  
  524. }
  525.