< prev index next >

src/java.base/share/classes/java/lang/System.java

Print this page

  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.BufferedInputStream;
  28 import java.io.BufferedOutputStream;
  29 import java.io.Console;
  30 import java.io.FileDescriptor;
  31 import java.io.FileInputStream;
  32 import java.io.FileOutputStream;
  33 import java.io.IOException;
  34 import java.io.InputStream;

  35 import java.io.PrintStream;
  36 import java.lang.annotation.Annotation;
  37 import java.lang.invoke.MethodHandle;
  38 import java.lang.invoke.MethodType;
  39 import java.lang.invoke.StringConcatFactory;
  40 import java.lang.module.ModuleDescriptor;
  41 import java.lang.reflect.Constructor;
  42 import java.lang.reflect.Executable;
  43 import java.lang.reflect.Method;
  44 import java.lang.reflect.Modifier;
  45 import java.net.URI;
  46 import java.net.URL;
  47 import java.nio.channels.Channel;
  48 import java.nio.channels.spi.SelectorProvider;
  49 import java.nio.charset.CharacterCodingException;
  50 import java.nio.charset.Charset;
  51 import java.security.AccessControlContext;
  52 import java.security.AccessController;
  53 import java.security.CodeSource;
  54 import java.security.PrivilegedAction;
  55 import java.security.ProtectionDomain;
  56 import java.util.Collections;
  57 import java.util.List;
  58 import java.util.Map;
  59 import java.util.Objects;
  60 import java.util.Properties;
  61 import java.util.PropertyPermission;
  62 import java.util.ResourceBundle;
  63 import java.util.Set;
  64 import java.util.WeakHashMap;

  65 import java.util.function.Supplier;
  66 import java.util.concurrent.ConcurrentHashMap;
  67 import java.util.stream.Stream;
  68 import jdk.internal.misc.Unsafe;
  69 import jdk.internal.util.StaticProperty;
  70 import jdk.internal.module.ModuleBootstrap;
  71 import jdk.internal.module.ServicesCatalog;
  72 import jdk.internal.reflect.CallerSensitive;
  73 import jdk.internal.reflect.Reflection;
  74 import jdk.internal.access.JavaLangAccess;
  75 import jdk.internal.access.SharedSecrets;
  76 import jdk.internal.misc.VM;
  77 import jdk.internal.logger.LoggerFinderLoader;
  78 import jdk.internal.logger.LazyLoggers;
  79 import jdk.internal.logger.LocalizedLoggerWrapper;
  80 import jdk.internal.util.SystemProps;




  81 import jdk.internal.vm.annotation.IntrinsicCandidate;
  82 import jdk.internal.vm.annotation.Stable;


  83 import sun.nio.fs.DefaultFileSystemProvider;
  84 import sun.reflect.annotation.AnnotationType;
  85 import sun.nio.ch.Interruptible;
  86 import sun.nio.cs.UTF_8;
  87 import sun.security.util.SecurityConstants;
  88 
  89 /**
  90  * The {@code System} class contains several useful class fields
  91  * and methods. It cannot be instantiated.
  92  *
  93  * Among the facilities provided by the {@code System} class
  94  * are standard input, standard output, and error output streams;
  95  * access to externally defined properties and environment
  96  * variables; a means of loading files and libraries; and a utility
  97  * method for quickly copying a portion of an array.
  98  *
  99  * @since   1.0
 100  */
 101 public final class System {
 102     /* Register the natives via the static initializer.

2014     public static void loadLibrary(String libname) {
2015         Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);
2016     }
2017 
2018     /**
2019      * Maps a library name into a platform-specific string representing
2020      * a native library.
2021      *
2022      * @param      libname the name of the library.
2023      * @return     a platform-dependent native library name.
2024      * @throws     NullPointerException if {@code libname} is {@code null}
2025      * @see        java.lang.System#loadLibrary(java.lang.String)
2026      * @see        java.lang.ClassLoader#findLibrary(java.lang.String)
2027      * @since      1.2
2028      */
2029     public static native String mapLibraryName(String libname);
2030 
2031     /**
2032      * Create PrintStream for stdout/err based on encoding.
2033      */
2034     private static PrintStream newPrintStream(FileOutputStream fos, String enc) {
2035         if (enc != null) {
2036             return new PrintStream(new BufferedOutputStream(fos, 128), true,
2037                                    Charset.forName(enc, UTF_8.INSTANCE));
2038         }
2039         return new PrintStream(new BufferedOutputStream(fos, 128), true);
2040     }
2041 
2042     /**
2043      * Logs an exception/error at initialization time to stdout or stderr.
2044      *
2045      * @param printToStderr to print to stderr rather than stdout
2046      * @param printStackTrace to print the stack trace
2047      * @param msg the message to print before the exception, can be {@code null}
2048      * @param e the exception or error
2049      */
2050     private static void logInitException(boolean printToStderr,
2051                                          boolean printStackTrace,
2052                                          String msg,
2053                                          Throwable e) {
2054         if (VM.initLevel() < 1) {
2055             throw new InternalError("system classes not initialized");
2056         }
2057         PrintStream log = (printToStderr) ? err : out;
2058         if (msg != null) {
2059             log.println(msg);

2131         var jnuEncoding = props.getProperty("sun.jnu.encoding");
2132         if (jnuEncoding == null || !Charset.isSupported(jnuEncoding)) {
2133             notSupportedJnuEncoding = jnuEncoding == null ? "null" : jnuEncoding;
2134             props.setProperty("sun.jnu.encoding", "UTF-8");
2135         }
2136 
2137         StaticProperty.javaHome();          // Load StaticProperty to cache the property values
2138 
2139         lineSeparator = props.getProperty("line.separator");
2140 
2141         FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
2142         FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
2143         FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
2144         setIn0(new BufferedInputStream(fdIn));
2145         // sun.stdout/err.encoding are set when the VM is associated with the terminal,
2146         // thus they are equivalent to Console.charset(), otherwise the encoding
2147         // defaults to native.encoding
2148         setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding", StaticProperty.nativeEncoding())));
2149         setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding", StaticProperty.nativeEncoding())));
2150 




2151         // Setup Java signal handlers for HUP, TERM, and INT (where available).
2152         Terminator.setup();
2153 
2154         // Initialize any miscellaneous operating system settings that need to be
2155         // set for the class libraries. Currently this is no-op everywhere except
2156         // for Windows where the process-wide error mode is set before the java.io
2157         // classes are used.
2158         VM.initializeOSEnvironment();
2159 
2160         // The main thread is not added to its thread group in the same
2161         // way as other threads; we must do it ourselves here.
2162         Thread current = Thread.currentThread();
2163         current.getThreadGroup().add(current);
2164 
2165         // Subsystems that are invoked during initialization can invoke
2166         // VM.isBooted() in order to avoid doing things that should
2167         // wait until the VM is fully initialized. The initialization level
2168         // is incremented from 0 to 1 here to indicate the first phase of
2169         // initialization has completed.
2170         // IMPORTANT: Ensure that this remains the last initialization action!
2171         VM.initLevel(1);
2172     }
2173 
2174     // @see #initPhase2()
2175     static ModuleLayer bootLayer;
2176 
2177     /*
2178      * Invoked by VM.  Phase 2 module system initialization.
2179      * Only classes in java.base can be loaded in this phase.
2180      *
2181      * @param printToStderr print exceptions to stderr rather than stdout
2182      * @param printStackTrace print stack trace when exception occurs
2183      *
2184      * @return JNI_OK for success, JNI_ERR for failure

2473                 return StringConcatHelper.mix(lengthCoder, constant);
2474             }
2475 
2476             public String join(String prefix, String suffix, String delimiter, String[] elements, int size) {
2477                 return String.join(prefix, suffix, delimiter, elements, size);
2478             }
2479 
2480             public Object classData(Class<?> c) {
2481                 return c.getClassData();
2482             }
2483 
2484             @Override
2485             public long findNative(ClassLoader loader, String entry) {
2486                 return ClassLoader.findNative(loader, entry);
2487             }
2488 
2489             @Override
2490             public void exit(int statusCode) {
2491                 Shutdown.exit(statusCode);
2492             }


























































































2493         });
2494     }
2495 }

  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.BufferedInputStream;
  28 import java.io.BufferedOutputStream;
  29 import java.io.Console;
  30 import java.io.FileDescriptor;
  31 import java.io.FileInputStream;
  32 import java.io.FileOutputStream;
  33 import java.io.IOException;
  34 import java.io.InputStream;
  35 import java.io.OutputStream;
  36 import java.io.PrintStream;
  37 import java.lang.annotation.Annotation;
  38 import java.lang.invoke.MethodHandle;
  39 import java.lang.invoke.MethodType;
  40 import java.lang.invoke.StringConcatFactory;
  41 import java.lang.module.ModuleDescriptor;
  42 import java.lang.reflect.Constructor;
  43 import java.lang.reflect.Executable;
  44 import java.lang.reflect.Method;
  45 import java.lang.reflect.Modifier;
  46 import java.net.URI;
  47 import java.net.URL;
  48 import java.nio.channels.Channel;
  49 import java.nio.channels.spi.SelectorProvider;
  50 import java.nio.charset.CharacterCodingException;
  51 import java.nio.charset.Charset;
  52 import java.security.AccessControlContext;
  53 import java.security.AccessController;
  54 import java.security.CodeSource;
  55 import java.security.PrivilegedAction;
  56 import java.security.ProtectionDomain;
  57 import java.util.Collections;
  58 import java.util.List;
  59 import java.util.Map;
  60 import java.util.Objects;
  61 import java.util.Properties;
  62 import java.util.PropertyPermission;
  63 import java.util.ResourceBundle;
  64 import java.util.Set;
  65 import java.util.WeakHashMap;
  66 import java.util.concurrent.Callable;
  67 import java.util.function.Supplier;
  68 import java.util.concurrent.ConcurrentHashMap;
  69 import java.util.stream.Stream;
  70 import jdk.internal.misc.Unsafe;
  71 import jdk.internal.util.StaticProperty;
  72 import jdk.internal.module.ModuleBootstrap;
  73 import jdk.internal.module.ServicesCatalog;
  74 import jdk.internal.reflect.CallerSensitive;
  75 import jdk.internal.reflect.Reflection;
  76 import jdk.internal.access.JavaLangAccess;
  77 import jdk.internal.access.SharedSecrets;
  78 import jdk.internal.misc.VM;
  79 import jdk.internal.logger.LoggerFinderLoader;
  80 import jdk.internal.logger.LazyLoggers;
  81 import jdk.internal.logger.LocalizedLoggerWrapper;
  82 import jdk.internal.util.SystemProps;
  83 import jdk.internal.vm.Continuation;
  84 import jdk.internal.vm.ContinuationScope;
  85 import jdk.internal.vm.StackableScope;
  86 import jdk.internal.vm.ThreadContainer;
  87 import jdk.internal.vm.annotation.IntrinsicCandidate;
  88 import jdk.internal.vm.annotation.Stable;
  89 import jdk.internal.vm.annotation.ChangesCurrentThread;
  90 import sun.nio.ch.ConsoleStreams;
  91 import sun.nio.fs.DefaultFileSystemProvider;
  92 import sun.reflect.annotation.AnnotationType;
  93 import sun.nio.ch.Interruptible;
  94 import sun.nio.cs.UTF_8;
  95 import sun.security.util.SecurityConstants;
  96 
  97 /**
  98  * The {@code System} class contains several useful class fields
  99  * and methods. It cannot be instantiated.
 100  *
 101  * Among the facilities provided by the {@code System} class
 102  * are standard input, standard output, and error output streams;
 103  * access to externally defined properties and environment
 104  * variables; a means of loading files and libraries; and a utility
 105  * method for quickly copying a portion of an array.
 106  *
 107  * @since   1.0
 108  */
 109 public final class System {
 110     /* Register the natives via the static initializer.

2022     public static void loadLibrary(String libname) {
2023         Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);
2024     }
2025 
2026     /**
2027      * Maps a library name into a platform-specific string representing
2028      * a native library.
2029      *
2030      * @param      libname the name of the library.
2031      * @return     a platform-dependent native library name.
2032      * @throws     NullPointerException if {@code libname} is {@code null}
2033      * @see        java.lang.System#loadLibrary(java.lang.String)
2034      * @see        java.lang.ClassLoader#findLibrary(java.lang.String)
2035      * @since      1.2
2036      */
2037     public static native String mapLibraryName(String libname);
2038 
2039     /**
2040      * Create PrintStream for stdout/err based on encoding.
2041      */
2042     private static PrintStream newPrintStream(OutputStream out, String enc) {
2043         if (enc != null) {
2044             return new PrintStream(new BufferedOutputStream(out, 128), true,
2045                                    Charset.forName(enc, UTF_8.INSTANCE));
2046         }
2047         return new PrintStream(new BufferedOutputStream(out, 128), true);
2048     }
2049 
2050     /**
2051      * Logs an exception/error at initialization time to stdout or stderr.
2052      *
2053      * @param printToStderr to print to stderr rather than stdout
2054      * @param printStackTrace to print the stack trace
2055      * @param msg the message to print before the exception, can be {@code null}
2056      * @param e the exception or error
2057      */
2058     private static void logInitException(boolean printToStderr,
2059                                          boolean printStackTrace,
2060                                          String msg,
2061                                          Throwable e) {
2062         if (VM.initLevel() < 1) {
2063             throw new InternalError("system classes not initialized");
2064         }
2065         PrintStream log = (printToStderr) ? err : out;
2066         if (msg != null) {
2067             log.println(msg);

2139         var jnuEncoding = props.getProperty("sun.jnu.encoding");
2140         if (jnuEncoding == null || !Charset.isSupported(jnuEncoding)) {
2141             notSupportedJnuEncoding = jnuEncoding == null ? "null" : jnuEncoding;
2142             props.setProperty("sun.jnu.encoding", "UTF-8");
2143         }
2144 
2145         StaticProperty.javaHome();          // Load StaticProperty to cache the property values
2146 
2147         lineSeparator = props.getProperty("line.separator");
2148 
2149         FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
2150         FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
2151         FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
2152         setIn0(new BufferedInputStream(fdIn));
2153         // sun.stdout/err.encoding are set when the VM is associated with the terminal,
2154         // thus they are equivalent to Console.charset(), otherwise the encoding
2155         // defaults to native.encoding
2156         setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding", StaticProperty.nativeEncoding())));
2157         setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding", StaticProperty.nativeEncoding())));
2158 
2159 //        setIn0(new BufferedInputStream(ConsoleStreams.in));
2160 //        setOut0(newPrintStream(ConsoleStreams.out, props.getProperty("sun.stdout.encoding")));
2161 //        setErr0(newPrintStream(ConsoleStreams.err, props.getProperty("sun.stderr.encoding")));
2162 
2163         // Setup Java signal handlers for HUP, TERM, and INT (where available).
2164         Terminator.setup();
2165 
2166         // Initialize any miscellaneous operating system settings that need to be
2167         // set for the class libraries. Currently this is no-op everywhere except
2168         // for Windows where the process-wide error mode is set before the java.io
2169         // classes are used.
2170         VM.initializeOSEnvironment();
2171 





2172         // Subsystems that are invoked during initialization can invoke
2173         // VM.isBooted() in order to avoid doing things that should
2174         // wait until the VM is fully initialized. The initialization level
2175         // is incremented from 0 to 1 here to indicate the first phase of
2176         // initialization has completed.
2177         // IMPORTANT: Ensure that this remains the last initialization action!
2178         VM.initLevel(1);
2179     }
2180 
2181     // @see #initPhase2()
2182     static ModuleLayer bootLayer;
2183 
2184     /*
2185      * Invoked by VM.  Phase 2 module system initialization.
2186      * Only classes in java.base can be loaded in this phase.
2187      *
2188      * @param printToStderr print exceptions to stderr rather than stdout
2189      * @param printStackTrace print stack trace when exception occurs
2190      *
2191      * @return JNI_OK for success, JNI_ERR for failure

2480                 return StringConcatHelper.mix(lengthCoder, constant);
2481             }
2482 
2483             public String join(String prefix, String suffix, String delimiter, String[] elements, int size) {
2484                 return String.join(prefix, suffix, delimiter, elements, size);
2485             }
2486 
2487             public Object classData(Class<?> c) {
2488                 return c.getClassData();
2489             }
2490 
2491             @Override
2492             public long findNative(ClassLoader loader, String entry) {
2493                 return ClassLoader.findNative(loader, entry);
2494             }
2495 
2496             @Override
2497             public void exit(int statusCode) {
2498                 Shutdown.exit(statusCode);
2499             }
2500 
2501             public Thread[] getAllThreads() {
2502                 return Thread.getAllThreads();
2503             }
2504 
2505             public ThreadContainer threadContainer(Thread thread) {
2506                 return thread.threadContainer();
2507             }
2508 
2509             public void start(Thread thread, ThreadContainer container) {
2510                 thread.start(container);
2511             }
2512 
2513             public StackableScope headStackableScope(Thread thread) {
2514                 return thread.headStackableScopes();
2515             }
2516 
2517             public void setHeadStackableScope(StackableScope scope) {
2518                 Thread.setHeadStackableScope(scope);
2519             }
2520 
2521             public Thread currentCarrierThread() {
2522                 return Thread.currentCarrierThread();
2523             }
2524 
2525             @ChangesCurrentThread
2526             public <V> V executeOnCarrierThread(Callable<V> task) throws Exception {
2527                 Thread thread = Thread.currentThread();
2528                 if (thread.isVirtual()) {
2529                     Thread carrier = Thread.currentCarrierThread();
2530                     carrier.setCurrentThread(carrier);
2531                     try {
2532                         return task.call();
2533                     } finally {
2534                         carrier.setCurrentThread(thread);
2535                     }
2536                 } else {
2537                     return task.call();
2538                 }
2539             }
2540 
2541             public <T> T getCarrierThreadLocal(ThreadLocal<T> local) {
2542                 return local.getCarrierThreadLocal();
2543             }
2544 
2545             public <T> void setCarrierThreadLocal(ThreadLocal<T> local, T value) {
2546                 local.setCarrierThreadLocal(value);
2547             }
2548 
2549             public Object[] scopeLocalCache() {
2550                 if (! ScopeLocal.PRESERVE_SCOPE_LOCAL_CACHE) {
2551                     return Thread.scopeLocalCache();
2552                 } else {
2553                     return null;
2554                 }
2555             }
2556 
2557             public void setScopeLocalCache(Object[] cache) {
2558                 Thread.setScopeLocalCache(cache);
2559             }
2560 
2561             public Object scopeLocalBindings() {
2562                 return Thread.scopeLocalBindings();
2563             }
2564 
2565             public Continuation getContinuation(Thread thread) {
2566                 return thread.getContinuation();
2567             }
2568 
2569             public void setContinuation(Thread thread, Continuation continuation) {
2570                 thread.setContinuation(continuation);
2571             }
2572 
2573             public void parkVirtualThread() {
2574                 ((VirtualThread) Thread.currentThread()).park();
2575             }
2576 
2577             public void parkVirtualThread(long nanos) {
2578                 ((VirtualThread) Thread.currentThread()).parkNanos(nanos);
2579             }
2580 
2581             public void unparkVirtualThread(Thread thread) {
2582                 ((VirtualThread) thread).unpark();
2583             }
2584 
2585             public StackWalker newStackWalkerInstance(Set<StackWalker.Option> options,
2586                                                       ContinuationScope contScope,
2587                                                       Continuation continuation) {
2588                 return StackWalker.newInstance(options, null, contScope, continuation);
2589             }
2590         });
2591     }
2592 }
< prev index next >