jdk/src/java.base/share/classes/sun/misc/VM.java
changeset 35233 357bf863e7c1
parent 35232 76aed99c0ddd
parent 34918 80f67512daa1
child 35234 854fc566323e
equal deleted inserted replaced
35232:76aed99c0ddd 35233:357bf863e7c1
     1 /*
       
     2  * Copyright (c) 1996, 2015, 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 
       
    26 package sun.misc;
       
    27 
       
    28 import static java.lang.Thread.State.*;
       
    29 import java.util.Properties;
       
    30 
       
    31 public class VM {
       
    32 
       
    33     /* The following methods used to be native methods that instruct
       
    34      * the VM to selectively suspend certain threads in low-memory
       
    35      * situations. They are inherently dangerous and not implementable
       
    36      * on native threads. We removed them in JDK 1.2. The skeletons
       
    37      * remain so that existing applications that use these methods
       
    38      * will still work.
       
    39      */
       
    40     private static boolean suspended = false;
       
    41 
       
    42     /** @deprecated */
       
    43     @Deprecated
       
    44     public static boolean threadsSuspended() {
       
    45         return suspended;
       
    46     }
       
    47 
       
    48     @SuppressWarnings("deprecation")
       
    49     public static boolean allowThreadSuspension(ThreadGroup g, boolean b) {
       
    50         return g.allowThreadSuspension(b);
       
    51     }
       
    52 
       
    53     /** @deprecated */
       
    54     @Deprecated
       
    55     public static boolean suspendThreads() {
       
    56         suspended = true;
       
    57         return true;
       
    58     }
       
    59 
       
    60     // Causes any suspended threadgroups to be resumed.
       
    61     /** @deprecated */
       
    62     @Deprecated
       
    63     public static void unsuspendThreads() {
       
    64         suspended = false;
       
    65     }
       
    66 
       
    67     // Causes threadgroups no longer marked suspendable to be resumed.
       
    68     /** @deprecated */
       
    69     @Deprecated
       
    70     public static void unsuspendSomeThreads() {
       
    71     }
       
    72 
       
    73     /* Deprecated fields and methods -- Memory advice not supported in 1.2 */
       
    74 
       
    75     /** @deprecated */
       
    76     @Deprecated
       
    77     public static final int STATE_GREEN = 1;
       
    78 
       
    79     /** @deprecated */
       
    80     @Deprecated
       
    81     public static final int STATE_YELLOW = 2;
       
    82 
       
    83     /** @deprecated */
       
    84     @Deprecated
       
    85     public static final int STATE_RED = 3;
       
    86 
       
    87     /** @deprecated */
       
    88     @Deprecated
       
    89     public static final int getState() {
       
    90         return STATE_GREEN;
       
    91     }
       
    92 
       
    93     /** @deprecated */
       
    94     @Deprecated
       
    95     public static void registerVMNotification(VMNotification n) { }
       
    96 
       
    97     /** @deprecated */
       
    98     @Deprecated
       
    99     public static void asChange(int as_old, int as_new) { }
       
   100 
       
   101     /** @deprecated */
       
   102     @Deprecated
       
   103     public static void asChange_otherthread(int as_old, int as_new) { }
       
   104 
       
   105     /*
       
   106      * Not supported in 1.2 because these will have to be exported as
       
   107      * JVM functions, and we are not sure we want do that. Leaving
       
   108      * here so it can be easily resurrected -- just remove the //
       
   109      * comments.
       
   110      */
       
   111 
       
   112     /**
       
   113      * Resume Java profiling.  All profiling data is added to any
       
   114      * earlier profiling, unless <code>resetJavaProfiler</code> is
       
   115      * called in between.  If profiling was not started from the
       
   116      * command line, <code>resumeJavaProfiler</code> will start it.
       
   117      * <p>
       
   118      *
       
   119      * NOTE: Profiling must be enabled from the command line for a
       
   120      * java.prof report to be automatically generated on exit; if not,
       
   121      * writeJavaProfilerReport must be invoked to write a report.
       
   122      *
       
   123      * @see     resetJavaProfiler
       
   124      * @see     writeJavaProfilerReport
       
   125      */
       
   126 
       
   127     // public native static void resumeJavaProfiler();
       
   128 
       
   129     /**
       
   130      * Suspend Java profiling.
       
   131      */
       
   132     // public native static void suspendJavaProfiler();
       
   133 
       
   134     /**
       
   135      * Initialize Java profiling.  Any accumulated profiling
       
   136      * information is discarded.
       
   137      */
       
   138     // public native static void resetJavaProfiler();
       
   139 
       
   140     /**
       
   141      * Write the current profiling contents to the file "java.prof".
       
   142      * If the file already exists, it will be overwritten.
       
   143      */
       
   144     // public native static void writeJavaProfilerReport();
       
   145 
       
   146 
       
   147     private static volatile boolean booted = false;
       
   148     private static final Object lock = new Object();
       
   149 
       
   150     // Invoked by System.initializeSystemClass just before returning.
       
   151     // Subsystems that are invoked during initialization can check this
       
   152     // property in order to avoid doing things that should wait until the
       
   153     // application class loader has been set up.
       
   154     //
       
   155     public static void booted() {
       
   156         synchronized (lock) {
       
   157             booted = true;
       
   158             lock.notifyAll();
       
   159         }
       
   160     }
       
   161 
       
   162     public static boolean isBooted() {
       
   163         return booted;
       
   164     }
       
   165 
       
   166     // Waits until VM completes initialization
       
   167     //
       
   168     // This method is invoked by the Finalizer thread
       
   169     public static void awaitBooted() throws InterruptedException {
       
   170         synchronized (lock) {
       
   171             while (!booted) {
       
   172                 lock.wait();
       
   173             }
       
   174         }
       
   175     }
       
   176 
       
   177     // A user-settable upper limit on the maximum amount of allocatable direct
       
   178     // buffer memory.  This value may be changed during VM initialization if
       
   179     // "java" is launched with "-XX:MaxDirectMemorySize=<size>".
       
   180     //
       
   181     // The initial value of this field is arbitrary; during JRE initialization
       
   182     // it will be reset to the value specified on the command line, if any,
       
   183     // otherwise to Runtime.getRuntime().maxMemory().
       
   184     //
       
   185     private static long directMemory = 64 * 1024 * 1024;
       
   186 
       
   187     // Returns the maximum amount of allocatable direct buffer memory.
       
   188     // The directMemory variable is initialized during system initialization
       
   189     // in the saveAndRemoveProperties method.
       
   190     //
       
   191     public static long maxDirectMemory() {
       
   192         return directMemory;
       
   193     }
       
   194 
       
   195     // User-controllable flag that determines if direct buffers should be page
       
   196     // aligned. The "-XX:+PageAlignDirectMemory" option can be used to force
       
   197     // buffers, allocated by ByteBuffer.allocateDirect, to be page aligned.
       
   198     private static boolean pageAlignDirectMemory;
       
   199 
       
   200     // Returns {@code true} if the direct buffers should be page aligned. This
       
   201     // variable is initialized by saveAndRemoveProperties.
       
   202     public static boolean isDirectMemoryPageAligned() {
       
   203         return pageAlignDirectMemory;
       
   204     }
       
   205 
       
   206     /**
       
   207      * Returns true if the given class loader is in the system domain
       
   208      * in which all permissions are granted.
       
   209      */
       
   210     public static boolean isSystemDomainLoader(ClassLoader loader) {
       
   211         return loader == null;
       
   212     }
       
   213 
       
   214     /**
       
   215      * Returns the system property of the specified key saved at
       
   216      * system initialization time.  This method should only be used
       
   217      * for the system properties that are not changed during runtime.
       
   218      * It accesses a private copy of the system properties so
       
   219      * that user's locking of the system properties object will not
       
   220      * cause the library to deadlock.
       
   221      *
       
   222      * Note that the saved system properties do not include
       
   223      * the ones set by sun.misc.Version.init().
       
   224      *
       
   225      */
       
   226     public static String getSavedProperty(String key) {
       
   227         if (savedProps.isEmpty())
       
   228             throw new IllegalStateException("Should be non-empty if initialized");
       
   229 
       
   230         return savedProps.getProperty(key);
       
   231     }
       
   232 
       
   233     // TODO: the Property Management needs to be refactored and
       
   234     // the appropriate prop keys need to be accessible to the
       
   235     // calling classes to avoid duplication of keys.
       
   236     private static final Properties savedProps = new Properties();
       
   237 
       
   238     // Save a private copy of the system properties and remove
       
   239     // the system properties that are not intended for public access.
       
   240     //
       
   241     // This method can only be invoked during system initialization.
       
   242     public static void saveAndRemoveProperties(Properties props) {
       
   243         if (booted)
       
   244             throw new IllegalStateException("System initialization has completed");
       
   245 
       
   246         savedProps.putAll(props);
       
   247 
       
   248         // Set the maximum amount of direct memory.  This value is controlled
       
   249         // by the vm option -XX:MaxDirectMemorySize=<size>.
       
   250         // The maximum amount of allocatable direct buffer memory (in bytes)
       
   251         // from the system property sun.nio.MaxDirectMemorySize set by the VM.
       
   252         // The system property will be removed.
       
   253         String s = (String)props.remove("sun.nio.MaxDirectMemorySize");
       
   254         if (s != null) {
       
   255             if (s.equals("-1")) {
       
   256                 // -XX:MaxDirectMemorySize not given, take default
       
   257                 directMemory = Runtime.getRuntime().maxMemory();
       
   258             } else {
       
   259                 long l = Long.parseLong(s);
       
   260                 if (l > -1)
       
   261                     directMemory = l;
       
   262             }
       
   263         }
       
   264 
       
   265         // Check if direct buffers should be page aligned
       
   266         s = (String)props.remove("sun.nio.PageAlignDirectMemory");
       
   267         if ("true".equals(s))
       
   268             pageAlignDirectMemory = true;
       
   269 
       
   270         // Remove other private system properties
       
   271         // used by java.lang.Integer.IntegerCache
       
   272         props.remove("java.lang.Integer.IntegerCache.high");
       
   273 
       
   274         // used by sun.launcher.LauncherHelper
       
   275         props.remove("sun.java.launcher.diag");
       
   276     }
       
   277 
       
   278     // Initialize any miscellenous operating system settings that need to be
       
   279     // set for the class libraries.
       
   280     //
       
   281     public static void initializeOSEnvironment() {
       
   282         if (!booted) {
       
   283             OSEnvironment.initialize();
       
   284         }
       
   285     }
       
   286 
       
   287     /* Current count of objects pending for finalization */
       
   288     private static volatile int finalRefCount;
       
   289 
       
   290     /* Peak count of objects pending for finalization */
       
   291     private static volatile int peakFinalRefCount;
       
   292 
       
   293     /*
       
   294      * Gets the number of objects pending for finalization.
       
   295      *
       
   296      * @return the number of objects pending for finalization.
       
   297      */
       
   298     public static int getFinalRefCount() {
       
   299         return finalRefCount;
       
   300     }
       
   301 
       
   302     /*
       
   303      * Gets the peak number of objects pending for finalization.
       
   304      *
       
   305      * @return the peak number of objects pending for finalization.
       
   306      */
       
   307     public static int getPeakFinalRefCount() {
       
   308         return peakFinalRefCount;
       
   309     }
       
   310 
       
   311     /*
       
   312      * Add {@code n} to the objects pending for finalization count.
       
   313      *
       
   314      * @param n an integer value to be added to the objects pending
       
   315      * for finalization count
       
   316      */
       
   317     public static void addFinalRefCount(int n) {
       
   318         // The caller must hold lock to synchronize the update.
       
   319 
       
   320         finalRefCount += n;
       
   321         if (finalRefCount > peakFinalRefCount) {
       
   322             peakFinalRefCount = finalRefCount;
       
   323         }
       
   324     }
       
   325 
       
   326     /**
       
   327      * Returns Thread.State for the given threadStatus
       
   328      */
       
   329     public static Thread.State toThreadState(int threadStatus) {
       
   330         if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) {
       
   331             return RUNNABLE;
       
   332         } else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) {
       
   333             return BLOCKED;
       
   334         } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) {
       
   335             return WAITING;
       
   336         } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) {
       
   337             return TIMED_WAITING;
       
   338         } else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) {
       
   339             return TERMINATED;
       
   340         } else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) {
       
   341             return NEW;
       
   342         } else {
       
   343             return RUNNABLE;
       
   344         }
       
   345     }
       
   346 
       
   347     /* The threadStatus field is set by the VM at state transition
       
   348      * in the hotspot implementation. Its value is set according to
       
   349      * the JVM TI specification GetThreadState function.
       
   350      */
       
   351     private static final int JVMTI_THREAD_STATE_ALIVE = 0x0001;
       
   352     private static final int JVMTI_THREAD_STATE_TERMINATED = 0x0002;
       
   353     private static final int JVMTI_THREAD_STATE_RUNNABLE = 0x0004;
       
   354     private static final int JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER = 0x0400;
       
   355     private static final int JVMTI_THREAD_STATE_WAITING_INDEFINITELY = 0x0010;
       
   356     private static final int JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT = 0x0020;
       
   357 
       
   358     /*
       
   359      * Returns the first non-null class loader up the execution stack,
       
   360      * or null if only code from the null class loader is on the stack.
       
   361      */
       
   362     public static native ClassLoader latestUserDefinedLoader();
       
   363 
       
   364     /**
       
   365      * Returns {@code true} if we are in a set UID program.
       
   366      */
       
   367     public static boolean isSetUID() {
       
   368         long uid = getuid();
       
   369         long euid = geteuid();
       
   370         long gid = getgid();
       
   371         long egid = getegid();
       
   372         return uid != euid  || gid != egid;
       
   373     }
       
   374 
       
   375     /**
       
   376      * Returns the real user ID of the calling process,
       
   377      * or -1 if the value is not available.
       
   378      */
       
   379     public static native long getuid();
       
   380 
       
   381     /**
       
   382      * Returns the effective user ID of the calling process,
       
   383      * or -1 if the value is not available.
       
   384      */
       
   385     public static native long geteuid();
       
   386 
       
   387     /**
       
   388      * Returns the real group ID of the calling process,
       
   389      * or -1 if the value is not available.
       
   390      */
       
   391     public static native long getgid();
       
   392 
       
   393     /**
       
   394      * Returns the effective group ID of the calling process,
       
   395      * or -1 if the value is not available.
       
   396      */
       
   397     public static native long getegid();
       
   398 
       
   399     /**
       
   400      * Get a nanosecond time stamp adjustment in the form of a single long.
       
   401      *
       
   402      * This value can be used to create an instant using
       
   403      * {@link java.time.Instant#ofEpochSecond(long, long)
       
   404      *  java.time.Instant.ofEpochSecond(offsetInSeconds,
       
   405      *  getNanoTimeAdjustment(offsetInSeconds))}.
       
   406      * <p>
       
   407      * The value returned has the best resolution available to the JVM on
       
   408      * the current system.
       
   409      * This is usually down to microseconds - or tenth of microseconds -
       
   410      * depending on the OS/Hardware and the JVM implementation.
       
   411      *
       
   412      * @param offsetInSeconds The offset in seconds from which the nanosecond
       
   413      *        time stamp should be computed.
       
   414      *
       
   415      * @apiNote The offset should be recent enough - so that
       
   416      *         {@code offsetInSeconds} is within {@code +/- 2^32} seconds of the
       
   417      *         current UTC time. If the offset is too far off, {@code -1} will be
       
   418      *         returned. As such, {@code -1} must not be considered as a valid
       
   419      *         nano time adjustment, but as an exception value indicating
       
   420      *         that an offset closer to the current time should be used.
       
   421      *
       
   422      * @return A nanosecond time stamp adjustment in the form of a single long.
       
   423      *     If the offset is too far off the current time, this method returns -1.
       
   424      *     In that case, the caller should call this method again, passing a
       
   425      *     more accurate offset.
       
   426      */
       
   427     public static native long getNanoTimeAdjustment(long offsetInSeconds);
       
   428 
       
   429     static {
       
   430         initialize();
       
   431     }
       
   432     private static native void initialize();
       
   433 }