Save This Page
Home » openjdk-7 » java » lang » [javadoc | source]
    1   /*
    2    * Copyright 1994-2007 Sun Microsystems, Inc.  All Rights Reserved.
    3    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    4    *
    5    * This code is free software; you can redistribute it and/or modify it
    6    * under the terms of the GNU General Public License version 2 only, as
    7    * published by the Free Software Foundation.  Sun designates this
    8    * particular file as subject to the "Classpath" exception as provided
    9    * by Sun in the LICENSE file that accompanied this code.
   10    *
   11    * This code is distributed in the hope that it will be useful, but WITHOUT
   12    * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   13    * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   14    * version 2 for more details (a copy is included in the LICENSE file that
   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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   22    * CA 95054 USA or visit www.sun.com if you need additional information or
   23    * have any questions.
   24    */
   25   package java.lang;
   26   
   27   import java.io;
   28   import java.util.Properties;
   29   import java.util.PropertyPermission;
   30   import java.util.StringTokenizer;
   31   import java.security.AccessController;
   32   import java.security.PrivilegedAction;
   33   import java.security.AllPermission;
   34   import java.nio.channels.Channel;
   35   import java.nio.channels.spi.SelectorProvider;
   36   import sun.nio.ch.Interruptible;
   37   import sun.net.InetAddressCachePolicy;
   38   import sun.reflect.Reflection;
   39   import sun.security.util.SecurityConstants;
   40   import sun.reflect.annotation.AnnotationType;
   41   
   42   /**
   43    * The <code>System</code> class contains several useful class fields
   44    * and methods. It cannot be instantiated.
   45    *
   46    * <p>Among the facilities provided by the <code>System</code> class
   47    * are standard input, standard output, and error output streams;
   48    * access to externally defined properties and environment
   49    * variables; a means of loading files and libraries; and a utility
   50    * method for quickly copying a portion of an array.
   51    *
   52    * @author  unascribed
   53    * @since   JDK1.0
   54    */
   55   public final class System {
   56   
   57       /* First thing---register the natives */
   58       private static native void registerNatives();
   59       static {
   60           registerNatives();
   61       }
   62   
   63       /** Don't let anyone instantiate this class */
   64       private System() {
   65       }
   66   
   67       /**
   68        * The "standard" input stream. This stream is already
   69        * open and ready to supply input data. Typically this stream
   70        * corresponds to keyboard input or another input source specified by
   71        * the host environment or user.
   72        */
   73       public final static InputStream in = nullInputStream();
   74   
   75       /**
   76        * The "standard" output stream. This stream is already
   77        * open and ready to accept output data. Typically this stream
   78        * corresponds to display output or another output destination
   79        * specified by the host environment or user.
   80        * <p>
   81        * For simple stand-alone Java applications, a typical way to write
   82        * a line of output data is:
   83        * <blockquote><pre>
   84        *     System.out.println(data)
   85        * </pre></blockquote>
   86        * <p>
   87        * See the <code>println</code> methods in class <code>PrintStream</code>.
   88        *
   89        * @see     java.io.PrintStream#println()
   90        * @see     java.io.PrintStream#println(boolean)
   91        * @see     java.io.PrintStream#println(char)
   92        * @see     java.io.PrintStream#println(char[])
   93        * @see     java.io.PrintStream#println(double)
   94        * @see     java.io.PrintStream#println(float)
   95        * @see     java.io.PrintStream#println(int)
   96        * @see     java.io.PrintStream#println(long)
   97        * @see     java.io.PrintStream#println(java.lang.Object)
   98        * @see     java.io.PrintStream#println(java.lang.String)
   99        */
  100       public final static PrintStream out = nullPrintStream();
  101   
  102       /**
  103        * The "standard" error output stream. This stream is already
  104        * open and ready to accept output data.
  105        * <p>
  106        * Typically this stream corresponds to display output or another
  107        * output destination specified by the host environment or user. By
  108        * convention, this output stream is used to display error messages
  109        * or other information that should come to the immediate attention
  110        * of a user even if the principal output stream, the value of the
  111        * variable <code>out</code>, has been redirected to a file or other
  112        * destination that is typically not continuously monitored.
  113        */
  114       public final static PrintStream err = nullPrintStream();
  115   
  116       /* The security manager for the system.
  117        */
  118       private static volatile SecurityManager security = null;
  119   
  120       /**
  121        * Reassigns the "standard" input stream.
  122        *
  123        * <p>First, if there is a security manager, its <code>checkPermission</code>
  124        * method is called with a <code>RuntimePermission("setIO")</code> permission
  125        *  to see if it's ok to reassign the "standard" input stream.
  126        * <p>
  127        *
  128        * @param in the new standard input stream.
  129        *
  130        * @throws SecurityException
  131        *        if a security manager exists and its
  132        *        <code>checkPermission</code> method doesn't allow
  133        *        reassigning of the standard input stream.
  134        *
  135        * @see SecurityManager#checkPermission
  136        * @see java.lang.RuntimePermission
  137        *
  138        * @since   JDK1.1
  139        */
  140       public static void setIn(InputStream in) {
  141           checkIO();
  142           setIn0(in);
  143       }
  144   
  145       /**
  146        * Reassigns the "standard" output stream.
  147        *
  148        * <p>First, if there is a security manager, its <code>checkPermission</code>
  149        * method is called with a <code>RuntimePermission("setIO")</code> permission
  150        *  to see if it's ok to reassign the "standard" output stream.
  151        *
  152        * @param out the new standard output stream
  153        *
  154        * @throws SecurityException
  155        *        if a security manager exists and its
  156        *        <code>checkPermission</code> method doesn't allow
  157        *        reassigning of the standard output stream.
  158        *
  159        * @see SecurityManager#checkPermission
  160        * @see java.lang.RuntimePermission
  161        *
  162        * @since   JDK1.1
  163        */
  164       public static void setOut(PrintStream out) {
  165           checkIO();
  166           setOut0(out);
  167       }
  168   
  169       /**
  170        * Reassigns the "standard" error output stream.
  171        *
  172        * <p>First, if there is a security manager, its <code>checkPermission</code>
  173        * method is called with a <code>RuntimePermission("setIO")</code> permission
  174        *  to see if it's ok to reassign the "standard" error output stream.
  175        *
  176        * @param err the new standard error output stream.
  177        *
  178        * @throws SecurityException
  179        *        if a security manager exists and its
  180        *        <code>checkPermission</code> method doesn't allow
  181        *        reassigning of the standard error output stream.
  182        *
  183        * @see SecurityManager#checkPermission
  184        * @see java.lang.RuntimePermission
  185        *
  186        * @since   JDK1.1
  187        */
  188       public static void setErr(PrintStream err) {
  189           checkIO();
  190           setErr0(err);
  191       }
  192   
  193       private static volatile Console cons = null;
  194       /**
  195        * Returns the unique {@link java.io.Console Console} object associated
  196        * with the current Java virtual machine, if any.
  197        *
  198        * @return  The system console, if any, otherwise <tt>null</tt>.
  199        *
  200        * @since   1.6
  201        */
  202        public static Console console() {
  203            if (cons == null) {
  204                synchronized (System.class) {
  205                    cons = sun.misc.SharedSecrets.getJavaIOAccess().console();
  206                }
  207            }
  208            return cons;
  209        }
  210   
  211       /**
  212        * Returns the channel inherited from the entity that created this
  213        * Java virtual machine.
  214        *
  215        * <p> This method returns the channel obtained by invoking the
  216        * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel
  217        * inheritedChannel} method of the system-wide default
  218        * {@link java.nio.channels.spi.SelectorProvider} object. </p>
  219        *
  220        * <p> In addition to the network-oriented channels described in
  221        * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel
  222        * inheritedChannel}, this method may return other kinds of
  223        * channels in the future.
  224        *
  225        * @return  The inherited channel, if any, otherwise <tt>null</tt>.
  226        *
  227        * @throws  IOException
  228        *          If an I/O error occurs
  229        *
  230        * @throws  SecurityException
  231        *          If a security manager is present and it does not
  232        *          permit access to the channel.
  233        *
  234        * @since 1.5
  235        */
  236       public static Channel inheritedChannel() throws IOException {
  237           return SelectorProvider.provider().inheritedChannel();
  238       }
  239   
  240       private static void checkIO() {
  241           SecurityManager sm = getSecurityManager();
  242           if (sm != null) {
  243               sm.checkPermission(new RuntimePermission("setIO"));
  244           }
  245       }
  246   
  247       private static native void setIn0(InputStream in);
  248       private static native void setOut0(PrintStream out);
  249       private static native void setErr0(PrintStream err);
  250   
  251       /**
  252        * Sets the System security.
  253        *
  254        * <p> If there is a security manager already installed, this method first
  255        * calls the security manager's <code>checkPermission</code> method
  256        * with a <code>RuntimePermission("setSecurityManager")</code>
  257        * permission to ensure it's ok to replace the existing
  258        * security manager.
  259        * This may result in throwing a <code>SecurityException</code>.
  260        *
  261        * <p> Otherwise, the argument is established as the current
  262        * security manager. If the argument is <code>null</code> and no
  263        * security manager has been established, then no action is taken and
  264        * the method simply returns.
  265        *
  266        * @param      s   the security manager.
  267        * @exception  SecurityException  if the security manager has already
  268        *             been set and its <code>checkPermission</code> method
  269        *             doesn't allow it to be replaced.
  270        * @see #getSecurityManager
  271        * @see SecurityManager#checkPermission
  272        * @see java.lang.RuntimePermission
  273        */
  274       public static
  275       void setSecurityManager(final SecurityManager s) {
  276           try {
  277               s.checkPackageAccess("java.lang");
  278           } catch (Exception e) {
  279               // no-op
  280           }
  281           setSecurityManager0(s);
  282       }
  283   
  284       private static synchronized
  285       void setSecurityManager0(final SecurityManager s) {
  286           SecurityManager sm = getSecurityManager();
  287           if (sm != null) {
  288               // ask the currently installed security manager if we
  289               // can replace it.
  290               sm.checkPermission(new RuntimePermission
  291                                        ("setSecurityManager"));
  292           }
  293   
  294           if ((s != null) && (s.getClass().getClassLoader() != null)) {
  295               // New security manager class is not on bootstrap classpath.
  296               // Cause policy to get initialized before we install the new
  297               // security manager, in order to prevent infinite loops when
  298               // trying to initialize the policy (which usually involves
  299               // accessing some security and/or system properties, which in turn
  300               // calls the installed security manager's checkPermission method
  301               // which will loop infinitely if there is a non-system class
  302               // (in this case: the new security manager class) on the stack).
  303               AccessController.doPrivileged(new PrivilegedAction<Object>() {
  304                   public Object run() {
  305                       s.getClass().getProtectionDomain().implies
  306                           (SecurityConstants.ALL_PERMISSION);
  307                       return null;
  308                   }
  309               });
  310           }
  311   
  312           security = s;
  313           InetAddressCachePolicy.setIfNotSet(InetAddressCachePolicy.FOREVER);
  314       }
  315   
  316       /**
  317        * Gets the system security interface.
  318        *
  319        * @return  if a security manager has already been established for the
  320        *          current application, then that security manager is returned;
  321        *          otherwise, <code>null</code> is returned.
  322        * @see     #setSecurityManager
  323        */
  324       public static SecurityManager getSecurityManager() {
  325           return security;
  326       }
  327   
  328       /**
  329        * Returns the current time in milliseconds.  Note that
  330        * while the unit of time of the return value is a millisecond,
  331        * the granularity of the value depends on the underlying
  332        * operating system and may be larger.  For example, many
  333        * operating systems measure time in units of tens of
  334        * milliseconds.
  335        *
  336        * <p> See the description of the class <code>Date</code> for
  337        * a discussion of slight discrepancies that may arise between
  338        * "computer time" and coordinated universal time (UTC).
  339        *
  340        * @return  the difference, measured in milliseconds, between
  341        *          the current time and midnight, January 1, 1970 UTC.
  342        * @see     java.util.Date
  343        */
  344       public static native long currentTimeMillis();
  345   
  346       /**
  347        * Returns the current value of the running Java Virtual Machine's
  348        * high-resolution time source, in nanoseconds.
  349        *
  350        * <p>This method can only be used to measure elapsed time and is
  351        * not related to any other notion of system or wall-clock time.
  352        * The value returned represents nanoseconds since some fixed but
  353        * arbitrary <i>origin</i> time (perhaps in the future, so values
  354        * may be negative).  The same origin is used by all invocations of
  355        * this method in an instance of a Java virtual machine; other
  356        * virtual machine instances are likely to use a different origin.
  357        *
  358        * <p>This method provides nanosecond precision, but not necessarily
  359        * nanosecond resolution (that is, how frequently the value changes)
  360        * - no guarantees are made except that the resolution is at least as
  361        * good as that of {@link #currentTimeMillis()}.
  362        *
  363        * <p>Differences in successive calls that span greater than
  364        * approximately 292 years (2<sup>63</sup> nanoseconds) will not
  365        * correctly compute elapsed time due to numerical overflow.
  366        *
  367        * <p>The values returned by this method become meaningful only when
  368        * the difference between two such values, obtained within the same
  369        * instance of a Java virtual machine, is computed.
  370        *
  371        * <p> For example, to measure how long some code takes to execute:
  372        *  <pre> {@code
  373        * long startTime = System.nanoTime();
  374        * // ... the code being measured ...
  375        * long estimatedTime = System.nanoTime() - startTime;}</pre>
  376        *
  377        * <p>To compare two nanoTime values
  378        *  <pre> {@code
  379        * long t0 = System.nanoTime();
  380        * ...
  381        * long t1 = System.nanoTime();}</pre>
  382        *
  383        * one should use {@code t1 - t0 < 0}, not {@code t1 < t0},
  384        * because of the possibility of numerical overflow.
  385        *
  386        * @return the current value of the running Java Virtual Machine's
  387        *         high-resolution time source, in nanoseconds
  388        * @since 1.5
  389        */
  390       public static native long nanoTime();
  391   
  392       /**
  393        * Copies an array from the specified source array, beginning at the
  394        * specified position, to the specified position of the destination array.
  395        * A subsequence of array components are copied from the source
  396        * array referenced by <code>src</code> to the destination array
  397        * referenced by <code>dest</code>. The number of components copied is
  398        * equal to the <code>length</code> argument. The components at
  399        * positions <code>srcPos</code> through
  400        * <code>srcPos+length-1</code> in the source array are copied into
  401        * positions <code>destPos</code> through
  402        * <code>destPos+length-1</code>, respectively, of the destination
  403        * array.
  404        * <p>
  405        * If the <code>src</code> and <code>dest</code> arguments refer to the
  406        * same array object, then the copying is performed as if the
  407        * components at positions <code>srcPos</code> through
  408        * <code>srcPos+length-1</code> were first copied to a temporary
  409        * array with <code>length</code> components and then the contents of
  410        * the temporary array were copied into positions
  411        * <code>destPos</code> through <code>destPos+length-1</code> of the
  412        * destination array.
  413        * <p>
  414        * If <code>dest</code> is <code>null</code>, then a
  415        * <code>NullPointerException</code> is thrown.
  416        * <p>
  417        * If <code>src</code> is <code>null</code>, then a
  418        * <code>NullPointerException</code> is thrown and the destination
  419        * array is not modified.
  420        * <p>
  421        * Otherwise, if any of the following is true, an
  422        * <code>ArrayStoreException</code> is thrown and the destination is
  423        * not modified:
  424        * <ul>
  425        * <li>The <code>src</code> argument refers to an object that is not an
  426        *     array.
  427        * <li>The <code>dest</code> argument refers to an object that is not an
  428        *     array.
  429        * <li>The <code>src</code> argument and <code>dest</code> argument refer
  430        *     to arrays whose component types are different primitive types.
  431        * <li>The <code>src</code> argument refers to an array with a primitive
  432        *    component type and the <code>dest</code> argument refers to an array
  433        *     with a reference component type.
  434        * <li>The <code>src</code> argument refers to an array with a reference
  435        *    component type and the <code>dest</code> argument refers to an array
  436        *     with a primitive component type.
  437        * </ul>
  438        * <p>
  439        * Otherwise, if any of the following is true, an
  440        * <code>IndexOutOfBoundsException</code> is
  441        * thrown and the destination is not modified:
  442        * <ul>
  443        * <li>The <code>srcPos</code> argument is negative.
  444        * <li>The <code>destPos</code> argument is negative.
  445        * <li>The <code>length</code> argument is negative.
  446        * <li><code>srcPos+length</code> is greater than
  447        *     <code>src.length</code>, the length of the source array.
  448        * <li><code>destPos+length</code> is greater than
  449        *     <code>dest.length</code>, the length of the destination array.
  450        * </ul>
  451        * <p>
  452        * Otherwise, if any actual component of the source array from
  453        * position <code>srcPos</code> through
  454        * <code>srcPos+length-1</code> cannot be converted to the component
  455        * type of the destination array by assignment conversion, an
  456        * <code>ArrayStoreException</code> is thrown. In this case, let
  457        * <b><i>k</i></b> be the smallest nonnegative integer less than
  458        * length such that <code>src[srcPos+</code><i>k</i><code>]</code>
  459        * cannot be converted to the component type of the destination
  460        * array; when the exception is thrown, source array components from
  461        * positions <code>srcPos</code> through
  462        * <code>srcPos+</code><i>k</i><code>-1</code>
  463        * will already have been copied to destination array positions
  464        * <code>destPos</code> through
  465        * <code>destPos+</code><i>k</I><code>-1</code> and no other
  466        * positions of the destination array will have been modified.
  467        * (Because of the restrictions already itemized, this
  468        * paragraph effectively applies only to the situation where both
  469        * arrays have component types that are reference types.)
  470        *
  471        * @param      src      the source array.
  472        * @param      srcPos   starting position in the source array.
  473        * @param      dest     the destination array.
  474        * @param      destPos  starting position in the destination data.
  475        * @param      length   the number of array elements to be copied.
  476        * @exception  IndexOutOfBoundsException  if copying would cause
  477        *               access of data outside array bounds.
  478        * @exception  ArrayStoreException  if an element in the <code>src</code>
  479        *               array could not be stored into the <code>dest</code> array
  480        *               because of a type mismatch.
  481        * @exception  NullPointerException if either <code>src</code> or
  482        *               <code>dest</code> is <code>null</code>.
  483        */
  484       public static native void arraycopy(Object src,  int  srcPos,
  485                                           Object dest, int destPos,
  486                                           int length);
  487   
  488       /**
  489        * Returns the same hash code for the given object as
  490        * would be returned by the default method hashCode(),
  491        * whether or not the given object's class overrides
  492        * hashCode().
  493        * The hash code for the null reference is zero.
  494        *
  495        * @param x object for which the hashCode is to be calculated
  496        * @return  the hashCode
  497        * @since   JDK1.1
  498        */
  499       public static native int identityHashCode(Object x);
  500   
  501       /**
  502        * System properties. The following properties are guaranteed to be defined:
  503        * <dl>
  504        * <dt>java.version         <dd>Java version number
  505        * <dt>java.vendor          <dd>Java vendor specific string
  506        * <dt>java.vendor.url      <dd>Java vendor URL
  507        * <dt>java.home            <dd>Java installation directory
  508        * <dt>java.class.version   <dd>Java class version number
  509        * <dt>java.class.path      <dd>Java classpath
  510        * <dt>os.name              <dd>Operating System Name
  511        * <dt>os.arch              <dd>Operating System Architecture
  512        * <dt>os.version           <dd>Operating System Version
  513        * <dt>file.separator       <dd>File separator ("/" on Unix)
  514        * <dt>path.separator       <dd>Path separator (":" on Unix)
  515        * <dt>line.separator       <dd>Line separator ("\n" on Unix)
  516        * <dt>user.name            <dd>User account name
  517        * <dt>user.home            <dd>User home directory
  518        * <dt>user.dir             <dd>User's current working directory
  519        * </dl>
  520        */
  521   
  522       private static Properties props;
  523       private static native Properties initProperties(Properties props);
  524   
  525       /**
  526        * Determines the current system properties.
  527        * <p>
  528        * First, if there is a security manager, its
  529        * <code>checkPropertiesAccess</code> method is called with no
  530        * arguments. This may result in a security exception.
  531        * <p>
  532        * The current set of system properties for use by the
  533        * {@link #getProperty(String)} method is returned as a
  534        * <code>Properties</code> object. If there is no current set of
  535        * system properties, a set of system properties is first created and
  536        * initialized. This set of system properties always includes values
  537        * for the following keys:
  538        * <table summary="Shows property keys and associated values">
  539        * <tr><th>Key</th>
  540        *     <th>Description of Associated Value</th></tr>
  541        * <tr><td><code>java.version</code></td>
  542        *     <td>Java Runtime Environment version</td></tr>
  543        * <tr><td><code>java.vendor</code></td>
  544        *     <td>Java Runtime Environment vendor</td></tr
  545        * <tr><td><code>java.vendor.url</code></td>
  546        *     <td>Java vendor URL</td></tr>
  547        * <tr><td><code>java.home</code></td>
  548        *     <td>Java installation directory</td></tr>
  549        * <tr><td><code>java.vm.specification.version</code></td>
  550        *     <td>Java Virtual Machine specification version</td></tr>
  551        * <tr><td><code>java.vm.specification.vendor</code></td>
  552        *     <td>Java Virtual Machine specification vendor</td></tr>
  553        * <tr><td><code>java.vm.specification.name</code></td>
  554        *     <td>Java Virtual Machine specification name</td></tr>
  555        * <tr><td><code>java.vm.version</code></td>
  556        *     <td>Java Virtual Machine implementation version</td></tr>
  557        * <tr><td><code>java.vm.vendor</code></td>
  558        *     <td>Java Virtual Machine implementation vendor</td></tr>
  559        * <tr><td><code>java.vm.name</code></td>
  560        *     <td>Java Virtual Machine implementation name</td></tr>
  561        * <tr><td><code>java.specification.version</code></td>
  562        *     <td>Java Runtime Environment specification  version</td></tr>
  563        * <tr><td><code>java.specification.vendor</code></td>
  564        *     <td>Java Runtime Environment specification  vendor</td></tr>
  565        * <tr><td><code>java.specification.name</code></td>
  566        *     <td>Java Runtime Environment specification  name</td></tr>
  567        * <tr><td><code>java.class.version</code></td>
  568        *     <td>Java class format version number</td></tr>
  569        * <tr><td><code>java.class.path</code></td>
  570        *     <td>Java class path</td></tr>
  571        * <tr><td><code>java.library.path</code></td>
  572        *     <td>List of paths to search when loading libraries</td></tr>
  573        * <tr><td><code>java.io.tmpdir</code></td>
  574        *     <td>Default temp file path</td></tr>
  575        * <tr><td><code>java.compiler</code></td>
  576        *     <td>Name of JIT compiler to use</td></tr>
  577        * <tr><td><code>java.ext.dirs</code></td>
  578        *     <td>Path of extension directory or directories</td></tr>
  579        * <tr><td><code>os.name</code></td>
  580        *     <td>Operating system name</td></tr>
  581        * <tr><td><code>os.arch</code></td>
  582        *     <td>Operating system architecture</td></tr>
  583        * <tr><td><code>os.version</code></td>
  584        *     <td>Operating system version</td></tr>
  585        * <tr><td><code>file.separator</code></td>
  586        *     <td>File separator ("/" on UNIX)</td></tr>
  587        * <tr><td><code>path.separator</code></td>
  588        *     <td>Path separator (":" on UNIX)</td></tr>
  589        * <tr><td><code>line.separator</code></td>
  590        *     <td>Line separator ("\n" on UNIX)</td></tr>
  591        * <tr><td><code>user.name</code></td>
  592        *     <td>User's account name</td></tr>
  593        * <tr><td><code>user.home</code></td>
  594        *     <td>User's home directory</td></tr>
  595        * <tr><td><code>user.dir</code></td>
  596        *     <td>User's current working directory</td></tr>
  597        * </table>
  598        * <p>
  599        * Multiple paths in a system property value are separated by the path
  600        * separator character of the platform.
  601        * <p>
  602        * Note that even if the security manager does not permit the
  603        * <code>getProperties</code> operation, it may choose to permit the
  604        * {@link #getProperty(String)} operation.
  605        *
  606        * @return     the system properties
  607        * @exception  SecurityException  if a security manager exists and its
  608        *             <code>checkPropertiesAccess</code> method doesn't allow access
  609        *              to the system properties.
  610        * @see        #setProperties
  611        * @see        java.lang.SecurityException
  612        * @see        java.lang.SecurityManager#checkPropertiesAccess()
  613        * @see        java.util.Properties
  614        */
  615       public static Properties getProperties() {
  616           SecurityManager sm = getSecurityManager();
  617           if (sm != null) {
  618               sm.checkPropertiesAccess();
  619           }
  620   
  621           return props;
  622       }
  623   
  624       /**
  625        * Sets the system properties to the <code>Properties</code>
  626        * argument.
  627        * <p>
  628        * First, if there is a security manager, its
  629        * <code>checkPropertiesAccess</code> method is called with no
  630        * arguments. This may result in a security exception.
  631        * <p>
  632        * The argument becomes the current set of system properties for use
  633        * by the {@link #getProperty(String)} method. If the argument is
  634        * <code>null</code>, then the current set of system properties is
  635        * forgotten.
  636        *
  637        * @param      props   the new system properties.
  638        * @exception  SecurityException  if a security manager exists and its
  639        *             <code>checkPropertiesAccess</code> method doesn't allow access
  640        *              to the system properties.
  641        * @see        #getProperties
  642        * @see        java.util.Properties
  643        * @see        java.lang.SecurityException
  644        * @see        java.lang.SecurityManager#checkPropertiesAccess()
  645        */
  646       public static void setProperties(Properties props) {
  647           SecurityManager sm = getSecurityManager();
  648           if (sm != null) {
  649               sm.checkPropertiesAccess();
  650           }
  651           if (props == null) {
  652               props = new Properties();
  653               initProperties(props);
  654           }
  655           System.props = props;
  656       }
  657   
  658       /**
  659        * Gets the system property indicated by the specified key.
  660        * <p>
  661        * First, if there is a security manager, its
  662        * <code>checkPropertyAccess</code> method is called with the key as
  663        * its argument. This may result in a SecurityException.
  664        * <p>
  665        * If there is no current set of system properties, a set of system
  666        * properties is first created and initialized in the same manner as
  667        * for the <code>getProperties</code> method.
  668        *
  669        * @param      key   the name of the system property.
  670        * @return     the string value of the system property,
  671        *             or <code>null</code> if there is no property with that key.
  672        *
  673        * @exception  SecurityException  if a security manager exists and its
  674        *             <code>checkPropertyAccess</code> method doesn't allow
  675        *              access to the specified system property.
  676        * @exception  NullPointerException if <code>key</code> is
  677        *             <code>null</code>.
  678        * @exception  IllegalArgumentException if <code>key</code> is empty.
  679        * @see        #setProperty
  680        * @see        java.lang.SecurityException
  681        * @see        java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
  682        * @see        java.lang.System#getProperties()
  683        */
  684       public static String getProperty(String key) {
  685           checkKey(key);
  686           SecurityManager sm = getSecurityManager();
  687           if (sm != null) {
  688               sm.checkPropertyAccess(key);
  689           }
  690   
  691           return props.getProperty(key);
  692       }
  693   
  694       /**
  695        * Gets the system property indicated by the specified key.
  696        * <p>
  697        * First, if there is a security manager, its
  698        * <code>checkPropertyAccess</code> method is called with the
  699        * <code>key</code> as its argument.
  700        * <p>
  701        * If there is no current set of system properties, a set of system
  702        * properties is first created and initialized in the same manner as
  703        * for the <code>getProperties</code> method.
  704        *
  705        * @param      key   the name of the system property.
  706        * @param      def   a default value.
  707        * @return     the string value of the system property,
  708        *             or the default value if there is no property with that key.
  709        *
  710        * @exception  SecurityException  if a security manager exists and its
  711        *             <code>checkPropertyAccess</code> method doesn't allow
  712        *             access to the specified system property.
  713        * @exception  NullPointerException if <code>key</code> is
  714        *             <code>null</code>.
  715        * @exception  IllegalArgumentException if <code>key</code> is empty.
  716        * @see        #setProperty
  717        * @see        java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
  718        * @see        java.lang.System#getProperties()
  719        */
  720       public static String getProperty(String key, String def) {
  721           checkKey(key);
  722           SecurityManager sm = getSecurityManager();
  723           if (sm != null) {
  724               sm.checkPropertyAccess(key);
  725           }
  726   
  727           return props.getProperty(key, def);
  728       }
  729   
  730       /**
  731        * Sets the system property indicated by the specified key.
  732        * <p>
  733        * First, if a security manager exists, its
  734        * <code>SecurityManager.checkPermission</code> method
  735        * is called with a <code>PropertyPermission(key, "write")</code>
  736        * permission. This may result in a SecurityException being thrown.
  737        * If no exception is thrown, the specified property is set to the given
  738        * value.
  739        * <p>
  740        *
  741        * @param      key   the name of the system property.
  742        * @param      value the value of the system property.
  743        * @return     the previous value of the system property,
  744        *             or <code>null</code> if it did not have one.
  745        *
  746        * @exception  SecurityException  if a security manager exists and its
  747        *             <code>checkPermission</code> method doesn't allow
  748        *             setting of the specified property.
  749        * @exception  NullPointerException if <code>key</code> or
  750        *             <code>value</code> is <code>null</code>.
  751        * @exception  IllegalArgumentException if <code>key</code> is empty.
  752        * @see        #getProperty
  753        * @see        java.lang.System#getProperty(java.lang.String)
  754        * @see        java.lang.System#getProperty(java.lang.String, java.lang.String)
  755        * @see        java.util.PropertyPermission
  756        * @see        SecurityManager#checkPermission
  757        * @since      1.2
  758        */
  759       public static String setProperty(String key, String value) {
  760           checkKey(key);
  761           SecurityManager sm = getSecurityManager();
  762           if (sm != null) {
  763               sm.checkPermission(new PropertyPermission(key,
  764                   SecurityConstants.PROPERTY_WRITE_ACTION));
  765           }
  766   
  767           return (String) props.setProperty(key, value);
  768       }
  769   
  770       /**
  771        * Removes the system property indicated by the specified key.
  772        * <p>
  773        * First, if a security manager exists, its
  774        * <code>SecurityManager.checkPermission</code> method
  775        * is called with a <code>PropertyPermission(key, "write")</code>
  776        * permission. This may result in a SecurityException being thrown.
  777        * If no exception is thrown, the specified property is removed.
  778        * <p>
  779        *
  780        * @param      key   the name of the system property to be removed.
  781        * @return     the previous string value of the system property,
  782        *             or <code>null</code> if there was no property with that key.
  783        *
  784        * @exception  SecurityException  if a security manager exists and its
  785        *             <code>checkPropertyAccess</code> method doesn't allow
  786        *              access to the specified system property.
  787        * @exception  NullPointerException if <code>key</code> is
  788        *             <code>null</code>.
  789        * @exception  IllegalArgumentException if <code>key</code> is empty.
  790        * @see        #getProperty
  791        * @see        #setProperty
  792        * @see        java.util.Properties
  793        * @see        java.lang.SecurityException
  794        * @see        java.lang.SecurityManager#checkPropertiesAccess()
  795        * @since 1.5
  796        */
  797       public static String clearProperty(String key) {
  798           checkKey(key);
  799           SecurityManager sm = getSecurityManager();
  800           if (sm != null) {
  801               sm.checkPermission(new PropertyPermission(key, "write"));
  802           }
  803   
  804           return (String) props.remove(key);
  805       }
  806   
  807       private static void checkKey(String key) {
  808           if (key == null) {
  809               throw new NullPointerException("key can't be null");
  810           }
  811           if (key.equals("")) {
  812               throw new IllegalArgumentException("key can't be empty");
  813           }
  814       }
  815   
  816       /**
  817        * Gets the value of the specified environment variable. An
  818        * environment variable is a system-dependent external named
  819        * value.
  820        *
  821        * <p>If a security manager exists, its
  822        * {@link SecurityManager#checkPermission checkPermission}
  823        * method is called with a
  824        * <code>{@link RuntimePermission}("getenv."+name)</code>
  825        * permission.  This may result in a {@link SecurityException}
  826        * being thrown.  If no exception is thrown the value of the
  827        * variable <code>name</code> is returned.
  828        *
  829        * <p><a name="EnvironmentVSSystemProperties"><i>System
  830        * properties</i> and <i>environment variables</i></a> are both
  831        * conceptually mappings between names and values.  Both
  832        * mechanisms can be used to pass user-defined information to a
  833        * Java process.  Environment variables have a more global effect,
  834        * because they are visible to all descendants of the process
  835        * which defines them, not just the immediate Java subprocess.
  836        * They can have subtly different semantics, such as case
  837        * insensitivity, on different operating systems.  For these
  838        * reasons, environment variables are more likely to have
  839        * unintended side effects.  It is best to use system properties
  840        * where possible.  Environment variables should be used when a
  841        * global effect is desired, or when an external system interface
  842        * requires an environment variable (such as <code>PATH</code>).
  843        *
  844        * <p>On UNIX systems the alphabetic case of <code>name</code> is
  845        * typically significant, while on Microsoft Windows systems it is
  846        * typically not.  For example, the expression
  847        * <code>System.getenv("FOO").equals(System.getenv("foo"))</code>
  848        * is likely to be true on Microsoft Windows.
  849        *
  850        * @param  name the name of the environment variable
  851        * @return the string value of the variable, or <code>null</code>
  852        *         if the variable is not defined in the system environment
  853        * @throws NullPointerException if <code>name</code> is <code>null</code>
  854        * @throws SecurityException
  855        *         if a security manager exists and its
  856        *         {@link SecurityManager#checkPermission checkPermission}
  857        *         method doesn't allow access to the environment variable
  858        *         <code>name</code>
  859        * @see    #getenv()
  860        * @see    ProcessBuilder#environment()
  861        */
  862       public static String getenv(String name) {
  863           SecurityManager sm = getSecurityManager();
  864           if (sm != null) {
  865               sm.checkPermission(new RuntimePermission("getenv."+name));
  866           }
  867   
  868           return ProcessEnvironment.getenv(name);
  869       }
  870   
  871   
  872       /**
  873        * Returns an unmodifiable string map view of the current system environment.
  874        * The environment is a system-dependent mapping from names to
  875        * values which is passed from parent to child processes.
  876        *
  877        * <p>If the system does not support environment variables, an
  878        * empty map is returned.
  879        *
  880        * <p>The returned map will never contain null keys or values.
  881        * Attempting to query the presence of a null key or value will
  882        * throw a {@link NullPointerException}.  Attempting to query
  883        * the presence of a key or value which is not of type
  884        * {@link String} will throw a {@link ClassCastException}.
  885        *
  886        * <p>The returned map and its collection views may not obey the
  887        * general contract of the {@link Object#equals} and
  888        * {@link Object#hashCode} methods.
  889        *
  890        * <p>The returned map is typically case-sensitive on all platforms.
  891        *
  892        * <p>If a security manager exists, its
  893        * {@link SecurityManager#checkPermission checkPermission}
  894        * method is called with a
  895        * <code>{@link RuntimePermission}("getenv.*")</code>
  896        * permission.  This may result in a {@link SecurityException} being
  897        * thrown.
  898        *
  899        * <p>When passing information to a Java subprocess,
  900        * <a href=#EnvironmentVSSystemProperties>system properties</a>
  901        * are generally preferred over environment variables.
  902        *
  903        * @return the environment as a map of variable names to values
  904        * @throws SecurityException
  905        *         if a security manager exists and its
  906        *         {@link SecurityManager#checkPermission checkPermission}
  907        *         method doesn't allow access to the process environment
  908        * @see    #getenv(String)
  909        * @see    ProcessBuilder#environment()
  910        * @since  1.5
  911        */
  912       public static java.util.Map<String,String> getenv() {
  913           SecurityManager sm = getSecurityManager();
  914           if (sm != null) {
  915               sm.checkPermission(new RuntimePermission("getenv.*"));
  916           }
  917   
  918           return ProcessEnvironment.getenv();
  919       }
  920   
  921       /**
  922        * Terminates the currently running Java Virtual Machine. The
  923        * argument serves as a status code; by convention, a nonzero status
  924        * code indicates abnormal termination.
  925        * <p>
  926        * This method calls the <code>exit</code> method in class
  927        * <code>Runtime</code>. This method never returns normally.
  928        * <p>
  929        * The call <code>System.exit(n)</code> is effectively equivalent to
  930        * the call:
  931        * <blockquote><pre>
  932        * Runtime.getRuntime().exit(n)
  933        * </pre></blockquote>
  934        *
  935        * @param      status   exit status.
  936        * @throws  SecurityException
  937        *        if a security manager exists and its <code>checkExit</code>
  938        *        method doesn't allow exit with the specified status.
  939        * @see        java.lang.Runtime#exit(int)
  940        */
  941       public static void exit(int status) {
  942           Runtime.getRuntime().exit(status);
  943       }
  944   
  945       /**
  946        * Runs the garbage collector.
  947        * <p>
  948        * Calling the <code>gc</code> method suggests that the Java Virtual
  949        * Machine expend effort toward recycling unused objects in order to
  950        * make the memory they currently occupy available for quick reuse.
  951        * When control returns from the method call, the Java Virtual
  952        * Machine has made a best effort to reclaim space from all discarded
  953        * objects.
  954        * <p>
  955        * The call <code>System.gc()</code> is effectively equivalent to the
  956        * call:
  957        * <blockquote><pre>
  958        * Runtime.getRuntime().gc()
  959        * </pre></blockquote>
  960        *
  961        * @see     java.lang.Runtime#gc()
  962        */
  963       public static void gc() {
  964           Runtime.getRuntime().gc();
  965       }
  966   
  967       /**
  968        * Runs the finalization methods of any objects pending finalization.
  969        * <p>
  970        * Calling this method suggests that the Java Virtual Machine expend
  971        * effort toward running the <code>finalize</code> methods of objects
  972        * that have been found to be discarded but whose <code>finalize</code>
  973        * methods have not yet been run. When control returns from the
  974        * method call, the Java Virtual Machine has made a best effort to
  975        * complete all outstanding finalizations.
  976        * <p>
  977        * The call <code>System.runFinalization()</code> is effectively
  978        * equivalent to the call:
  979        * <blockquote><pre>
  980        * Runtime.getRuntime().runFinalization()
  981        * </pre></blockquote>
  982        *
  983        * @see     java.lang.Runtime#runFinalization()
  984        */
  985       public static void runFinalization() {
  986           Runtime.getRuntime().runFinalization();
  987       }
  988   
  989       /**
  990        * Enable or disable finalization on exit; doing so specifies that the
  991        * finalizers of all objects that have finalizers that have not yet been
  992        * automatically invoked are to be run before the Java runtime exits.
  993        * By default, finalization on exit is disabled.
  994        *
  995        * <p>If there is a security manager,
  996        * its <code>checkExit</code> method is first called
  997        * with 0 as its argument to ensure the exit is allowed.
  998        * This could result in a SecurityException.
  999        *
 1000        * @deprecated  This method is inherently unsafe.  It may result in
 1001        *      finalizers being called on live objects while other threads are
 1002        *      concurrently manipulating those objects, resulting in erratic
 1003        *      behavior or deadlock.
 1004        * @param value indicating enabling or disabling of finalization
 1005        * @throws  SecurityException
 1006        *        if a security manager exists and its <code>checkExit</code>
 1007        *        method doesn't allow the exit.
 1008        *
 1009        * @see     java.lang.Runtime#exit(int)
 1010        * @see     java.lang.Runtime#gc()
 1011        * @see     java.lang.SecurityManager#checkExit(int)
 1012        * @since   JDK1.1
 1013        */
 1014       @Deprecated
 1015       public static void runFinalizersOnExit(boolean value) {
 1016           Runtime.getRuntime().runFinalizersOnExit(value);
 1017       }
 1018   
 1019       /**
 1020        * Loads a code file with the specified filename from the local file
 1021        * system as a dynamic library. The filename
 1022        * argument must be a complete path name.
 1023        * <p>
 1024        * The call <code>System.load(name)</code> is effectively equivalent
 1025        * to the call:
 1026        * <blockquote><pre>
 1027        * Runtime.getRuntime().load(name)
 1028        * </pre></blockquote>
 1029        *
 1030        * @param      filename   the file to load.
 1031        * @exception  SecurityException  if a security manager exists and its
 1032        *             <code>checkLink</code> method doesn't allow
 1033        *             loading of the specified dynamic library
 1034        * @exception  UnsatisfiedLinkError  if the file does not exist.
 1035        * @exception  NullPointerException if <code>filename</code> is
 1036        *             <code>null</code>
 1037        * @see        java.lang.Runtime#load(java.lang.String)
 1038        * @see        java.lang.SecurityManager#checkLink(java.lang.String)
 1039        */
 1040       public static void load(String filename) {
 1041           Runtime.getRuntime().load0(getCallerClass(), filename);
 1042       }
 1043   
 1044       /**
 1045        * Loads the system library specified by the <code>libname</code>
 1046        * argument. The manner in which a library name is mapped to the
 1047        * actual system library is system dependent.
 1048        * <p>
 1049        * The call <code>System.loadLibrary(name)</code> is effectively
 1050        * equivalent to the call
 1051        * <blockquote><pre>
 1052        * Runtime.getRuntime().loadLibrary(name)
 1053        * </pre></blockquote>
 1054        *
 1055        * @param      libname   the name of the library.
 1056        * @exception  SecurityException  if a security manager exists and its
 1057        *             <code>checkLink</code> method doesn't allow
 1058        *             loading of the specified dynamic library
 1059        * @exception  UnsatisfiedLinkError  if the library does not exist.
 1060        * @exception  NullPointerException if <code>libname</code> is
 1061        *             <code>null</code>
 1062        * @see        java.lang.Runtime#loadLibrary(java.lang.String)
 1063        * @see        java.lang.SecurityManager#checkLink(java.lang.String)
 1064        */
 1065       public static void loadLibrary(String libname) {
 1066           Runtime.getRuntime().loadLibrary0(getCallerClass(), libname);
 1067       }
 1068   
 1069       /**
 1070        * Maps a library name into a platform-specific string representing
 1071        * a native library.
 1072        *
 1073        * @param      libname the name of the library.
 1074        * @return     a platform-dependent native library name.
 1075        * @exception  NullPointerException if <code>libname</code> is
 1076        *             <code>null</code>
 1077        * @see        java.lang.System#loadLibrary(java.lang.String)
 1078        * @see        java.lang.ClassLoader#findLibrary(java.lang.String)
 1079        * @since      1.2
 1080        */
 1081       public static native String mapLibraryName(String libname);
 1082   
 1083       /**
 1084        * The following two methods exist because in, out, and err must be
 1085        * initialized to null.  The compiler, however, cannot be permitted to
 1086        * inline access to them, since they are later set to more sensible values
 1087        * by initializeSystemClass().
 1088        */
 1089       private static InputStream nullInputStream() throws NullPointerException {
 1090           if (currentTimeMillis() > 0) {
 1091               return null;
 1092           }
 1093           throw new NullPointerException();
 1094       }
 1095   
 1096       private static PrintStream nullPrintStream() throws NullPointerException {
 1097           if (currentTimeMillis() > 0) {
 1098               return null;
 1099           }
 1100           throw new NullPointerException();
 1101       }
 1102   
 1103       /**
 1104        * Initialize the system class.  Called after thread initialization.
 1105        */
 1106       private static void initializeSystemClass() {
 1107           props = new Properties();
 1108           initProperties(props);
 1109           sun.misc.Version.init();
 1110           FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
 1111           FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
 1112           FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
 1113           setIn0(new BufferedInputStream(fdIn));
 1114           setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
 1115           setErr0(new PrintStream(new BufferedOutputStream(fdErr, 128), true));
 1116   
 1117           // Load the zip library now in order to keep java.util.zip.ZipFile
 1118           // from trying to use itself to load this library later.
 1119           loadLibrary("zip");
 1120   
 1121           // Setup Java signal handlers for HUP, TERM, and INT (where available).
 1122           Terminator.setup();
 1123   
 1124           // The order in with the hooks are added here is important as it
 1125           // determines the order in which they are run.
 1126           // (1)Console restore hook needs to be called first.
 1127           // (2)Application hooks must be run before calling deleteOnExitHook.
 1128           Shutdown.add(sun.misc.SharedSecrets.getJavaIOAccess().consoleRestoreHook());
 1129           Shutdown.add(ApplicationShutdownHooks.hook());
 1130           Shutdown.add(sun.misc.SharedSecrets.getJavaIODeleteOnExitAccess());
 1131   
 1132           // Initialize any miscellenous operating system settings that need to be
 1133           // set for the class libraries. Currently this is no-op everywhere except
 1134           // for Windows where the process-wide error mode is set before the java.io
 1135           // classes are used.
 1136           sun.misc.VM.initializeOSEnvironment();
 1137   
 1138           // Set the maximum amount of direct memory.  This value is controlled
 1139           // by the vm option -XX:MaxDirectMemorySize=<size>.  This method acts
 1140           // as an initializer only if it is called before sun.misc.VM.booted().
 1141           sun.misc.VM.maxDirectMemory();
 1142   
 1143           // Set a boolean to determine whether ClassLoader.loadClass accepts
 1144           // array syntax.  This value is controlled by the system property
 1145           // "sun.lang.ClassLoader.allowArraySyntax".  This method acts as
 1146           // an initializer only if it is called before sun.misc.VM.booted().
 1147           sun.misc.VM.allowArraySyntax();
 1148   
 1149           // Subsystems that are invoked during initialization can invoke
 1150           // sun.misc.VM.isBooted() in order to avoid doing things that should
 1151           // wait until the application class loader has been set up.
 1152           sun.misc.VM.booted();
 1153   
 1154           // The main thread is not added to its thread group in the same
 1155           // way as other threads; we must do it ourselves here.
 1156           Thread current = Thread.currentThread();
 1157           current.getThreadGroup().add(current);
 1158   
 1159           // Allow privileged classes outside of java.lang
 1160           sun.misc.SharedSecrets.setJavaLangAccess(new sun.misc.JavaLangAccess(){
 1161               public sun.reflect.ConstantPool getConstantPool(Class klass) {
 1162                   return klass.getConstantPool();
 1163               }
 1164               public void setAnnotationType(Class klass, AnnotationType type) {
 1165                   klass.setAnnotationType(type);
 1166               }
 1167               public AnnotationType getAnnotationType(Class klass) {
 1168                   return klass.getAnnotationType();
 1169               }
 1170               public <E extends Enum<E>>
 1171                       E[] getEnumConstantsShared(Class<E> klass) {
 1172                   return klass.getEnumConstantsShared();
 1173               }
 1174               public void blockedOn(Thread t, Interruptible b) {
 1175                   t.blockedOn(b);
 1176               }
 1177           });
 1178       }
 1179   
 1180       /* returns the class of the caller. */
 1181       static Class getCallerClass() {
 1182           // NOTE use of more generic Reflection.getCallerClass()
 1183           return Reflection.getCallerClass(3);
 1184       }
 1185   }

Save This Page
Home » openjdk-7 » java » lang » [javadoc | source]