home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / 3rdParty / jbuilder / unsupported / JDK1.2beta3 / SOURCE / SRC.ZIP / java / lang / Runtime.java < prev    next >
Encoding:
Java Source  |  1998-03-20  |  21.6 KB  |  586 lines

  1. /*
  2.  * @(#)Runtime.java    1.41 98/03/18
  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.41, 03/18/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.      *
  40.      * @return  the <code>Runtime</code> object associated with the current
  41.      *          Java application.
  42.      */
  43.     public static Runtime getRuntime() { 
  44.     return currentRuntime;
  45.     }
  46.     
  47.     /** Don't let anyone else instantiate this class */
  48.     private Runtime() {}
  49.  
  50.     /* Helper for exit
  51.      */
  52.     private native void exitInternal(int status);
  53.  
  54.     /**
  55.      * Terminates the currently running Java Virtual Machine. This 
  56.      * method never returns normally. 
  57.      * <p>
  58.      * If there is a security manager, its <code>checkExit</code> method 
  59.      * is called with the status as its argument. This may result in a 
  60.      * security exception. 
  61.      * <p>
  62.      * The argument serves as a status code; by convention, a nonzero 
  63.      * status code indicates abnormal termination. 
  64.      *
  65.      * @param      status   exit status.
  66.      * @exception  SecurityException  if the current thread cannot exit with
  67.      *               the specified status.
  68.      * @see        java.lang.SecurityException
  69.      * @see        java.lang.SecurityManager#checkExit(int)
  70.      */
  71.     public void exit(int status) {
  72.     SecurityManager security = System.getSecurityManager();
  73.     if (security != null) {
  74.         security.checkExit(status);
  75.     }
  76.     exitInternal(status);
  77.     }
  78.  
  79.     /* Wormhole for calling java.lang.ref.Finalizer.setRunFinalizersOnExit */
  80.     private static native void runFinalizersOnExit0(boolean value);
  81.  
  82.     /**
  83.      * Enable or disable finalization on exit; doing so specifies that the
  84.      * finalizers of all objects that have finalizers that have not yet been
  85.      * automatically invoked are to be run before the Java runtime exits.
  86.      * By default, finalization on exit is disabled.  An invocation of
  87.      * the runFinalizersOnExit method is permitted only if the caller is
  88.      * allowed to exit, and is otherwise rejected by the security manager.
  89.      * @see Runtime#gc
  90.      * @see Runtime#exit
  91.      */
  92.     public static void runFinalizersOnExit(boolean value) {
  93.     SecurityManager security = System.getSecurityManager();
  94.     if (security != null) {
  95.         try {
  96.         security.checkExit(0); 
  97.         } catch (SecurityException e) {
  98.         throw new SecurityException("runFinalizersOnExit");
  99.         }
  100.     }
  101.     runFinalizersOnExit0(value);
  102.     }
  103.  
  104.     /* Helper for exec
  105.      */
  106.     private native Process execInternal(String cmdarray[], String envp[]) 
  107.      throws IOException;
  108.  
  109.     /**
  110.      * Executes the specified string command in a separate process. 
  111.      * <p>
  112.      * The <code>command</code> argument is parsed into tokens and then 
  113.      * executed as a command in a separate process. This method has 
  114.      * exactly the same effect as <code>exec(command, null)</code>. 
  115.      *
  116.      * @param      command   a specified system command.
  117.      * @return     a <code>Process</code> object for managing the subprocess.
  118.      * @exception  SecurityException  if the current thread cannot create a
  119.      *             subprocess.
  120.      * @see        java.lang.Runtime#exec(java.lang.String, java.lang.String[])
  121.      */
  122.     public Process exec(String command) throws IOException {
  123.     return exec(command, null);
  124.     }
  125.  
  126.     /**
  127.      * Executes the specified string command in a separate process with the 
  128.      * specified environment. 
  129.      * <p>
  130.      * This method breaks the <code>command</code> string into tokens and 
  131.      * creates a new array <code>cmdarray</code> containing the tokens; it 
  132.      * then performs the call <code>exec(cmdarray, envp)</code>. 
  133.      *
  134.      * @param      command   a specified system command.
  135.      * @param      envp      array containing environment in format
  136.      *                       <i>name</i>=<i>value</i>
  137.      * @return     a <code>Process</code> object for managing the subprocess.
  138.      * @exception  SecurityException  if the current thread cannot create a
  139.      *               subprocess.
  140.      * @see        java.lang.Runtime#exec(java.lang.String[], java.lang.String[])
  141.      */
  142.     public Process exec(String command, String envp[]) throws IOException {
  143.     int count = 0;
  144.     String cmdarray[];
  145.      StringTokenizer st;
  146.  
  147.     st = new StringTokenizer(command);
  148.      count = st.countTokens();
  149.  
  150.     cmdarray = new String[count];
  151.     st = new StringTokenizer(command);
  152.     count = 0;
  153.      while (st.hasMoreTokens()) {
  154.          cmdarray[count++] = st.nextToken();
  155.      }
  156.     SecurityManager security = System.getSecurityManager();
  157.     if (security != null) {
  158.         security.checkExec(cmdarray[0]);
  159.     }
  160.     return execInternal(cmdarray, envp);
  161.     }
  162.  
  163.     /**
  164.      * Executes the specified command and arguments in a separate process.
  165.      * <p>
  166.      * The command specified by the tokens in <code>cmdarray</code> is 
  167.      * executed as a command in a separate process. This has exactly the 
  168.      * same effect as <code>exec(cmdarray, null)</code>. 
  169.      *
  170.      * @param      cmdarray   array containing the command to call and
  171.      *                        its arguments.
  172.      * @return     a <code>Process</code> object for managing the subprocess.
  173.      * @exception  SecurityException  if the current thread cannot create a
  174.      *               subprocess.
  175.      * @see        java.lang.Runtime#exec(java.lang.String[], java.lang.String[])
  176.      */
  177.     public Process exec(String cmdarray[]) throws IOException {
  178.     return exec(cmdarray, null);
  179.     }
  180.  
  181.     /**
  182.      * Executes the specified command and arguments in a separate process
  183.      * with the specified environment. 
  184.      * <p>
  185.      * If there is a security manager, its <code>checkExec</code> method 
  186.      * is called with the first component of the array 
  187.      * <code>cmdarray</code> as its argument. This may result in a security 
  188.      * exception. 
  189.      * <p>
  190.      * Given an array of strings <code>cmdarray</code>, representing the 
  191.      * tokens of a command line, and an array of strings <code>envp</code>, 
  192.      * representing an "environment" that defines system 
  193.      * properties, this method creates a new process in which to execute 
  194.      * the specified command. 
  195.      *
  196.      * @param      cmdarray   array containing the command to call and
  197.      *                        its arguments.
  198.      * @param      envp       array containing environment in format
  199.      *                        <i>name</i>=<i>value</i>.
  200.      * @return     a <code>Process</code> object for managing the subprocess.
  201.      * @exception  SecurityException  if the current thread cannot create a
  202.      *               subprocess.
  203.      * @see     java.lang.SecurityException
  204.      * @see     java.lang.SecurityManager#checkExec(java.lang.String)
  205.      */
  206.     public Process exec(String cmdarray[], String envp[]) throws IOException {
  207.     SecurityManager security = System.getSecurityManager();
  208.     if (security != null) {
  209.         security.checkExec(cmdarray[0]);
  210.     }
  211.     return execInternal(cmdarray, envp);
  212.     }
  213.  
  214.     /**
  215.      * Returns the amount of free memory in the system. The value returned
  216.      * by this method is always less than the value returned by the
  217.      * <code>totalMemory</code> method. Calling the <code>gc</code> method may
  218.      * result in increasing the value returned by <code>freeMemory.</code>
  219.      *
  220.      * @return  an approximation to the total amount of memory currently
  221.      *          available for future allocated objects, measured in bytes.
  222.      */
  223.     public native long freeMemory();
  224.  
  225.     /**
  226.      * Returns the total amount of memory in the Java Virtual Machine. 
  227.      *
  228.      * @return  the total amount of memory currently available for allocating
  229.      *          objects, measured in bytes.
  230.      */
  231.     public native long totalMemory();
  232.  
  233.     /**
  234.      * Runs the garbage collector.
  235.      * Calling this method suggests that the Java Virtual Machine expend 
  236.      * effort toward recycling unused objects in order to make the memory 
  237.      * they currently occupy available for quick reuse. When control 
  238.      * returns from the method call, the Java Virtual Machine has made 
  239.      * its best effort to recycle all unused objects. 
  240.      * <p>
  241.      * The name <code>gc</code> stands for "garbage 
  242.      * collector". The Java Virtual Machine performs this recycling 
  243.      * process automatically as needed even if the <code>gc</code> method 
  244.      * is not invoked explicitly. 
  245.      */
  246.     public native void gc();
  247.  
  248.     /* Wormhole for calling java.lang.ref.Finalizer.runFinalization */
  249.     private static native void runFinalization0();
  250.  
  251.     /**
  252.      * Runs the finalization methods of any objects pending finalization.
  253.      * Calling this method suggests that the Java Virtual Machine expend 
  254.      * effort toward running the <code>finalize</code> methods of objects 
  255.      * that have been found to be discarded but whose <code>finalize</code> 
  256.      * methods have not yet been run. When control returns from the 
  257.      * method call, the Java Virtual Machine has made a best effort to 
  258.      * complete all outstanding finalizations. 
  259.      * <p>
  260.      * The Java Virtual Machine performs the finalization process 
  261.      * automatically as needed if the <code>runFinalization</code> method 
  262.      * is not invoked explicitly. 
  263.      *
  264.      * @see     java.lang.Object#finalize()
  265.      */
  266.     public void runFinalization() {
  267.     runFinalization0();
  268.     }
  269.  
  270.     /**
  271.      * Enables/Disables tracing of instructions.
  272.      * If the <code>boolean</code> argument is <code>true</code>, this 
  273.      * method asks the Java Virtual Machine to print out a detailed trace 
  274.      * of each instruction in the Java Virtual Machine as it is executed. 
  275.      * The virtual machine may ignore this request if it does not support 
  276.      * this feature. The destination of the trace output is system 
  277.      * dependent. 
  278.      * <p>
  279.      * If the <code>boolean</code> argument is <code>false</code>, this 
  280.      * method causes the Java Virtual Machine to stop performing the 
  281.      * detailed instruction trace it is performing. 
  282.      *
  283.      * @param   on   <code>true</code> to enable instruction tracing;
  284.      *               <code>false</code> to disable this feature.
  285.      */
  286.     public native void traceInstructions(boolean on);
  287.  
  288.     /**
  289.      * Enables/Disables tracing of method calls.
  290.      * If the <code>boolean</code> argument is <code>true</code>, this 
  291.      * method asks the Java Virtual Machine to print out a detailed trace 
  292.      * of each method in the Java Virtual Machine as it is called. The 
  293.      * virtual machine may ignore this request if it does not support 
  294.      * this feature. The destination of the trace output is system dependent. 
  295.      * <p>
  296.      * If the <code>boolean</code> argument is <code>false</code>, this 
  297.      * method causes the Java Virtual Machine to stop performing the 
  298.      * detailed method trace it is performing. 
  299.      *
  300.      * @param   on   <code>true</code> to enable instruction tracing;
  301.      *               <code>false</code> to disable this feature.
  302.      */
  303.     public native void traceMethodCalls(boolean on);
  304.  
  305.     /**
  306.      * Initializes the linker and returns the search path for shared libraries.
  307.      */
  308.     private native String buildLibName(String pathname, String filename);
  309.  
  310.     /* Helper for load and loadLibrary */
  311.     private boolean loadFileInternal(Class cls, String filename) {
  312.         File file = new File(filename);
  313.     String canonPath;
  314.     try {
  315.         canonPath = file.getCanonicalPath();
  316.     } catch (IOException e) {
  317.         return false;
  318.     }
  319.     return ClassLoader.loadLibrary(cls.getClassLoader(), canonPath);
  320.     }
  321.  
  322.     /** The paths searched for libraries */
  323.     private String paths[];
  324.  
  325.     private void initializeLinker() {
  326.     String ldpath = System.getProperty("java.library.path", "");
  327.     String ps = File.pathSeparator;
  328.     int ldlen = ldpath.length();
  329.     int i, j, n;
  330.     // Count the separators in the path
  331.     i = ldpath.indexOf(ps);
  332.     n = 0;
  333.     while (i >= 0) {
  334.         n++;
  335.         i = ldpath.indexOf(ps, i+1);
  336.     }
  337.  
  338.     // allocate the array of paths - n :'s = n + 1 path elements
  339.     paths = new String[n + 1];
  340.  
  341.     // Fill the array with paths from the ldpath
  342.     n = i = 0;
  343.     j = ldpath.indexOf(ps);
  344.     while (j >= 0) {
  345.         if (j - i > 0) {
  346.         paths[n++] = ldpath.substring(i, j);
  347.         } else if (j - i == 0) { 
  348.         paths[n++] = ".";
  349.         }
  350.         i = j + 1;
  351.         j = ldpath.indexOf(ps, i);
  352.     }
  353.     paths[n] = ldpath.substring(i, ldlen);
  354.     }
  355.  
  356.     /**
  357.      * Loads the specified filename as a dynamic library. The filename 
  358.      * argument must be a complete pathname. 
  359.      * From <code>java_g</code> it will automagically insert "_g" before the
  360.      * ".so" (for example
  361.      * <code>Runtime.getRuntime().load("/home/avh/lib/libX11.so");</code>).
  362.      * <p>
  363.      * If there is a security manager, its <code>checkLink</code> method 
  364.      * is called with the <code>filename</code> as its argument. This may 
  365.      * result in a security exception. 
  366.      *
  367.      * @param      filename   the file to load.
  368.      * @exception  SecurityException     if the current thread cannot load the
  369.      *               specified dynamic library.
  370.      * @exception  UnsatisfiedLinkError  if the file does not exist.
  371.      * @see        java.lang.Runtime#getRuntime()
  372.      * @see        java.lang.SecurityException
  373.      * @see        java.lang.SecurityManager#checkLink(java.lang.String)
  374.      */
  375.     public void load(String filename) {
  376.         load0(System.getCallerClass(), filename);
  377.     }
  378.  
  379.     synchronized void load0(Class cls, String filename) {
  380.     SecurityManager security = System.getSecurityManager();
  381.     if (security != null) {
  382.         security.checkLink(filename);
  383.     }
  384.     if (!loadFileInternal(cls, filename)) {
  385.         throw new UnsatisfiedLinkError(filename);
  386.     }   /* else load was successful; return */
  387.     }
  388.  
  389.     /**
  390.      * Loads the dynamic library with the specified library name. The 
  391.      * mapping from a library name to a specific filename is done in a 
  392.      * system-specific manner. 
  393.      * <p>
  394.      * First, if there is a security manager, its <code>checkLink</code> 
  395.      * method is called with the <code>filename</code> as its argument. 
  396.      * This may result in a security exception. 
  397.      * <p>
  398.      * If this method is called more than once with the same library 
  399.      * name, the second and subsequent calls are ignored. 
  400.      *
  401.      * @param      libname   the name of the library.
  402.      * @exception  SecurityException     if the current thread cannot load the
  403.      *               specified dynamic library.
  404.      * @exception  UnsatisfiedLinkError  if the library does not exist.
  405.      * @see        java.lang.SecurityException
  406.      * @see        java.lang.SecurityManager#checkLink(java.lang.String)
  407.      */
  408.     public void loadLibrary(String libname) {
  409.         loadLibrary0(System.getCallerClass(), libname); 
  410.     }
  411.  
  412.     synchronized void loadLibrary0(Class cls, String libname) {
  413.     SecurityManager security = System.getSecurityManager();
  414.     if (security != null) {
  415.         security.checkLink(libname);
  416.     }
  417.         if (paths == null) {
  418.             initializeLinker();
  419.     }
  420.     for (int i = 0 ; i < paths.length ; i++) {
  421.         String tempname = buildLibName(paths[i], libname);
  422.         if (loadFileInternal(cls, tempname)) {
  423.         return;
  424.         }
  425.     }
  426.     // Oops, it failed
  427.         throw new UnsatisfiedLinkError("no " + libname + 
  428.                        " in shared library path");
  429.     }
  430.  
  431.     /**
  432.      * Creates a localized version of an input stream. This method takes 
  433.      * an <code>InputStream</code> and returns an <code>InputStream</code> 
  434.      * equivalent to the argument in all respects except that it is 
  435.      * localized: as characters in the local character set are read from 
  436.      * the stream, they are automatically converted from the local 
  437.      * character set to Unicode. 
  438.      * <p>
  439.      * If the argument is already a localized stream, it may be returned 
  440.      * as the result. 
  441.      *
  442.      * @deprecated As of JDK 1.1, the preferred way translate a byte
  443.      * stream in the local encoding into a character stream in Unicode is via
  444.      * the <code>InputStreamReader</code> and <code>BufferedReader</code>
  445.      * classes.
  446.      *
  447.      * @return     a localized input stream.
  448.      * @see        java.io.InputStream
  449.      * @see        java.io.BufferedReader#BufferedReader(java.io.Reader)
  450.      * @see        java.io.InputStreamReader#InputStreamReader(java.io.InputStream)
  451.      */
  452.     public InputStream getLocalizedInputStream(InputStream in) {
  453.     return in;
  454.     }
  455.  
  456.     /**
  457.      * Creates a localized version of an output stream. This method 
  458.      * takes an <code>OutputStream</code> and returns an 
  459.      * <code>OutputStream</code> equivalent to the argument in all respects 
  460.      * except that it is localized: as Unicode characters are written to 
  461.      * the stream, they are automatically converted to the local 
  462.      * character set. 
  463.      * <p>
  464.      * If the argument is already a localized stream, it may be returned 
  465.      * as the result. 
  466.      *
  467.      * @deprecated As of JDK 1.1, the preferred way to translate a
  468.      * Unicode character stream into a byte stream in the local encoding is via
  469.      * the <code>OutputStreamWriter</code>, <code>BufferedWriter</code>, and
  470.      * <code>PrintWriter</code> classes.
  471.      *
  472.      * @return     a localized output stream.
  473.      * @see        java.io.OutputStream
  474.      * @see        java.io.BufferedWriter#BufferedWriter(java.io.Writer)
  475.      * @see        java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
  476.      * @see        java.io.PrintWriter#PrintWriter(java.io.OutputStream)
  477.      */
  478.     public OutputStream getLocalizedOutputStream(OutputStream out) {
  479.     return out;
  480.     }
  481.  
  482.  
  483.     /**
  484.      * The <code>MemoryAdvice</code> interface defines the values returned by
  485.      * the <code>getMemoryAdvice</code> and <code>waitForMemoryAdvice</code>
  486.      * methods of the <code>Runtime</code> class.  These methods allow a
  487.      * program to query the runtime system for advice about how it should
  488.      * manage its memory usage.  There are four increasingly-dire levels of
  489.      * advice.
  490.      *
  491.      * @see Runtime#waitForMemoryAdvice
  492.      * @see Runtime#getMemoryAdvice
  493.      * @since JDK1.2
  494.      */
  495.     static public interface MemoryAdvice {
  496.  
  497.     /**
  498.      * A memory-advice level of <code>GREEN</code> tells the program that
  499.      * no special actions are suggested.
  500.      */
  501.     public static final int GREEN = 0;
  502.  
  503.     /**
  504.      * A memory-advice level of <code>YELLOW</code> tells the program that
  505.      * it would be beneficial, but not essential, to discard some objects
  506.      * in the near future.  On a system with virtual memory, this level
  507.      * typically implies that the virtual machine will soon request
  508.      * additional memory resources.  If the maximum size of the heap is set
  509.      * when the virtual machine starts, this level typically implies that a
  510.      * preset low-memory threshold has been reached.  Note that these two
  511.      * conditions are not mutually exclusive.
  512.      */
  513.     public static final int YELLOW = 1;
  514.  
  515.     /**
  516.      * A memory-advice level of <code>ORANGE</code> tells the program that
  517.      * it should try to discard objects as soon as possible in order to
  518.      * maintain good performance.  On a system with virtual memory, this
  519.      * level typically implies that paging is imminent.  If the maximum
  520.      * size of the heap is set when the virtual machine starts, this level
  521.      * typically implies that a preset very-low-memory threshold has been
  522.      * reached.  Note that these two conditions are not mutually exclusive.
  523.      */
  524.     public static final int ORANGE = 2;
  525.  
  526.     /**
  527.      * A memory-advice level of <code>RED</code> tells the program that it
  528.      * should take every conceivable action to discard objects.  This level
  529.      * typically means that very little memory is left.  Any cleanup
  530.      * actions should, therefore, allocate as few objects as possible.
  531.      */
  532.     public static final int RED = 3;
  533.  
  534.     }
  535.  
  536.  
  537.     private int memoryAdvice = MemoryAdvice.GREEN;    /* Updated by GC */
  538.     private Object memoryAdviceLock = new Object();
  539.  
  540.     /**
  541.      * Wait until the memory-advice level is different from <code>level</code>.
  542.      * If the current level is different from <code>level</code>, return that
  543.      * level immediately.  Otherwise block until the level changes.
  544.      *
  545.      * <p> This method is intended primarily for use in the implementation of
  546.      * caches that flush cache entries according to the amount of memory
  547.      * available.
  548.      *
  549.      * @param  level  One of <code>GREEN</code>, <code>YELLOW</code>,
  550.      *                <code>ORANGE</code>, or <code>RED</code>; these
  551.      *                constants are defined in the
  552.      *                <code>Runtime.MemoryAdvice</code> interface
  553.      *
  554.      * @return  The new memory-advice level
  555.      *
  556.      * @exception InterruptedException  If the wait is interrupted
  557.      *
  558.      * @see Runtime#MemoryAdvice
  559.      * @since JDK1.2
  560.      */
  561.     public int waitForMemoryAdvice(int level) throws InterruptedException {
  562.     synchronized (memoryAdviceLock) {
  563.         int current;
  564.         for (;;) {
  565.         current = memoryAdvice;
  566.         if (current != level) break;
  567.         memoryAdviceLock.wait();
  568.         }
  569.         return current;
  570.     }
  571.     }
  572.  
  573.     /**
  574.      * Return the runtime system's current memory-advice level.
  575.      *
  576.      * @see Runtime#MemoryAdvice
  577.      * @since JDK1.2
  578.      */
  579.     public int getMemoryAdvice() {
  580.     synchronized (memoryAdviceLock) {
  581.         return memoryAdvice;
  582.     }
  583.     }
  584.  
  585. }
  586.