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

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