1 /*
   2  * Copyright (c) 1995, 2020, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2019, Azul Systems, Inc. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.  Oracle designates this
   9  * particular file as subject to the "Classpath" exception as provided
  10  * by Oracle in the LICENSE file that accompanied this code.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  23  * or visit www.oracle.com if you need additional information or have any
  24  * questions.
  25  */
  26 
  27 package java.lang;
  28 
  29 import java.io.*;
  30 import java.lang.reflect.Field;
  31 import java.math.BigInteger;
  32 import java.util.function.ToLongFunction;
  33 import java.util.regex.Matcher;
  34 import java.util.regex.Pattern;
  35 import java.util.stream.Collectors;
  36 import java.util.Arrays;
  37 import java.util.ArrayDeque;
  38 import java.util.List;
  39 import java.util.Objects;
  40 import java.util.Optional;
  41 import java.util.StringTokenizer;
  42 
  43 import jdk.internal.HotSpotIntrinsicCandidate;
  44 import jdk.internal.access.SharedSecrets;
  45 import jdk.internal.loader.NativeLibrary;
  46 import jdk.internal.reflect.CallerSensitive;
  47 import jdk.internal.reflect.Reflection;
  48 import jdk.internal.vm.annotation.DontInline;
  49 import sun.security.util.SecurityConstants;
  50 
  51 /**
  52  * Every Java application has a single instance of class
  53  * {@code Runtime} that allows the application to interface with
  54  * the environment in which the application is running. The current
  55  * runtime can be obtained from the {@code getRuntime} method.
  56  * <p>
  57  * An application cannot create its own instance of this class.
  58  *
  59  * @author  unascribed
  60  * @see     java.lang.Runtime#getRuntime()
  61  * @since   1.0
  62  */
  63 
  64 public class Runtime {
  65     private static final Runtime currentRuntime = new Runtime();
  66 
  67     private static Version version;
  68 
  69     /**
  70      * Returns the runtime object associated with the current Java application.
  71      * Most of the methods of class {@code Runtime} are instance
  72      * methods and must be invoked with respect to the current runtime object.
  73      *
  74      * @return  the {@code Runtime} object associated with the current
  75      *          Java application.
  76      */
  77     public static Runtime getRuntime() {
  78         return currentRuntime;
  79     }
  80 
  81     /** Don't let anyone else instantiate this class */
  82     private Runtime() {}
  83 
  84     /**
  85      * Terminates the currently running Java virtual machine by initiating its
  86      * shutdown sequence.  This method never returns normally.  The argument
  87      * serves as a status code; by convention, a nonzero status code indicates
  88      * abnormal termination.
  89      *
  90      * <p> All registered {@linkplain #addShutdownHook shutdown hooks}, if any,
  91      * are started in some unspecified order and allowed to run concurrently
  92      * until they finish.  Once this is done the virtual machine
  93      * {@linkplain #halt halts}.
  94      *
  95      * <p> If this method is invoked after all shutdown hooks have already
  96      * been run and the status is nonzero then this method halts the
  97      * virtual machine with the given status code. Otherwise, this method
  98      * blocks indefinitely.
  99      *
 100      * <p> The {@link System#exit(int) System.exit} method is the
 101      * conventional and convenient means of invoking this method.
 102      *
 103      * @param  status
 104      *         Termination status.  By convention, a nonzero status code
 105      *         indicates abnormal termination.
 106      *
 107      * @throws SecurityException
 108      *         If a security manager is present and its
 109      *         {@link SecurityManager#checkExit checkExit} method does not permit
 110      *         exiting with the specified status
 111      *
 112      * @see java.lang.SecurityException
 113      * @see java.lang.SecurityManager#checkExit(int)
 114      * @see #addShutdownHook
 115      * @see #removeShutdownHook
 116      * @see #halt(int)
 117      */
 118     public void exit(int status) {
 119         SecurityManager security = System.getSecurityManager();
 120         if (security != null) {
 121             security.checkExit(status);
 122         }
 123         Shutdown.exit(status);
 124     }
 125 
 126     /**
 127      * Registers a new virtual-machine shutdown hook.
 128      *
 129      * <p> The Java virtual machine <i>shuts down</i> in response to two kinds
 130      * of events:
 131      *
 132      *   <ul>
 133      *
 134      *   <li> The program <i>exits</i> normally, when the last non-daemon
 135      *   thread exits or when the {@link #exit exit} (equivalently,
 136      *   {@link System#exit(int) System.exit}) method is invoked, or
 137      *
 138      *   <li> The virtual machine is <i>terminated</i> in response to a
 139      *   user interrupt, such as typing {@code ^C}, or a system-wide event,
 140      *   such as user logoff or system shutdown.
 141      *
 142      *   </ul>
 143      *
 144      * <p> A <i>shutdown hook</i> is simply an initialized but unstarted
 145      * thread.  When the virtual machine begins its shutdown sequence it will
 146      * start all registered shutdown hooks in some unspecified order and let
 147      * them run concurrently.  When all the hooks have finished it will then
 148      * halt. Note that daemon threads will continue to run during the shutdown
 149      * sequence, as will non-daemon threads if shutdown was initiated by
 150      * invoking the {@link #exit exit} method.
 151      *
 152      * <p> Once the shutdown sequence has begun it can be stopped only by
 153      * invoking the {@link #halt halt} method, which forcibly
 154      * terminates the virtual machine.
 155      *
 156      * <p> Once the shutdown sequence has begun it is impossible to register a
 157      * new shutdown hook or de-register a previously-registered hook.
 158      * Attempting either of these operations will cause an
 159      * {@link IllegalStateException} to be thrown.
 160      *
 161      * <p> Shutdown hooks run at a delicate time in the life cycle of a virtual
 162      * machine and should therefore be coded defensively.  They should, in
 163      * particular, be written to be thread-safe and to avoid deadlocks insofar
 164      * as possible.  They should also not rely blindly upon services that may
 165      * have registered their own shutdown hooks and therefore may themselves in
 166      * the process of shutting down.  Attempts to use other thread-based
 167      * services such as the AWT event-dispatch thread, for example, may lead to
 168      * deadlocks.
 169      *
 170      * <p> Shutdown hooks should also finish their work quickly.  When a
 171      * program invokes {@link #exit exit} the expectation is
 172      * that the virtual machine will promptly shut down and exit.  When the
 173      * virtual machine is terminated due to user logoff or system shutdown the
 174      * underlying operating system may only allow a fixed amount of time in
 175      * which to shut down and exit.  It is therefore inadvisable to attempt any
 176      * user interaction or to perform a long-running computation in a shutdown
 177      * hook.
 178      *
 179      * <p> Uncaught exceptions are handled in shutdown hooks just as in any
 180      * other thread, by invoking the
 181      * {@link ThreadGroup#uncaughtException uncaughtException} method of the
 182      * thread's {@link ThreadGroup} object. The default implementation of this
 183      * method prints the exception's stack trace to {@link System#err} and
 184      * terminates the thread; it does not cause the virtual machine to exit or
 185      * halt.
 186      *
 187      * <p> In rare circumstances the virtual machine may <i>abort</i>, that is,
 188      * stop running without shutting down cleanly.  This occurs when the
 189      * virtual machine is terminated externally, for example with the
 190      * {@code SIGKILL} signal on Unix or the {@code TerminateProcess} call on
 191      * Microsoft Windows.  The virtual machine may also abort if a native
 192      * method goes awry by, for example, corrupting internal data structures or
 193      * attempting to access nonexistent memory.  If the virtual machine aborts
 194      * then no guarantee can be made about whether or not any shutdown hooks
 195      * will be run.
 196      *
 197      * @param   hook
 198      *          An initialized but unstarted {@link Thread} object
 199      *
 200      * @throws  IllegalArgumentException
 201      *          If the specified hook has already been registered,
 202      *          or if it can be determined that the hook is already running or
 203      *          has already been run
 204      *
 205      * @throws  IllegalStateException
 206      *          If the virtual machine is already in the process
 207      *          of shutting down
 208      *
 209      * @throws  SecurityException
 210      *          If a security manager is present and it denies
 211      *          {@link RuntimePermission}("shutdownHooks")
 212      *
 213      * @see #removeShutdownHook
 214      * @see #halt(int)
 215      * @see #exit(int)
 216      * @since 1.3
 217      */
 218     public void addShutdownHook(Thread hook) {
 219         SecurityManager sm = System.getSecurityManager();
 220         if (sm != null) {
 221             sm.checkPermission(new RuntimePermission("shutdownHooks"));
 222         }
 223         ApplicationShutdownHooks.add(hook);
 224     }
 225 
 226     /**
 227      * De-registers a previously-registered virtual-machine shutdown hook.
 228      *
 229      * @param hook the hook to remove
 230      * @return {@code true} if the specified hook had previously been
 231      * registered and was successfully de-registered, {@code false}
 232      * otherwise.
 233      *
 234      * @throws  IllegalStateException
 235      *          If the virtual machine is already in the process of shutting
 236      *          down
 237      *
 238      * @throws  SecurityException
 239      *          If a security manager is present and it denies
 240      *          {@link RuntimePermission}("shutdownHooks")
 241      *
 242      * @see #addShutdownHook
 243      * @see #exit(int)
 244      * @since 1.3
 245      */
 246     public boolean removeShutdownHook(Thread hook) {
 247         SecurityManager sm = System.getSecurityManager();
 248         if (sm != null) {
 249             sm.checkPermission(new RuntimePermission("shutdownHooks"));
 250         }
 251         return ApplicationShutdownHooks.remove(hook);
 252     }
 253 
 254     /**
 255      * Forcibly terminates the currently running Java virtual machine.  This
 256      * method never returns normally.
 257      *
 258      * <p> This method should be used with extreme caution.  Unlike the
 259      * {@link #exit exit} method, this method does not cause shutdown
 260      * hooks to be started.  If the shutdown sequence has already been
 261      * initiated then this method does not wait for any running
 262      * shutdown hooks to finish their work.
 263      *
 264      * @param  status
 265      *         Termination status. By convention, a nonzero status code
 266      *         indicates abnormal termination. If the {@link Runtime#exit exit}
 267      *         (equivalently, {@link System#exit(int) System.exit}) method
 268      *         has already been invoked then this status code
 269      *         will override the status code passed to that method.
 270      *
 271      * @throws SecurityException
 272      *         If a security manager is present and its
 273      *         {@link SecurityManager#checkExit checkExit} method
 274      *         does not permit an exit with the specified status
 275      *
 276      * @see #exit
 277      * @see #addShutdownHook
 278      * @see #removeShutdownHook
 279      * @since 1.3
 280      */
 281     public void halt(int status) {
 282         SecurityManager sm = System.getSecurityManager();
 283         if (sm != null) {
 284             sm.checkExit(status);
 285         }
 286         Shutdown.beforeHalt();
 287         Shutdown.halt(status);
 288     }
 289 
 290     /**
 291      * Executes the specified string command in a separate process.
 292      *
 293      * <p>This is a convenience method.  An invocation of the form
 294      * {@code exec(command)}
 295      * behaves in exactly the same way as the invocation
 296      * {@link #exec(String, String[], File) exec}{@code (command, null, null)}.
 297      *
 298      * @param   command   a specified system command.
 299      *
 300      * @return  A new {@link Process} object for managing the subprocess
 301      *
 302      * @throws  SecurityException
 303      *          If a security manager exists and its
 304      *          {@link SecurityManager#checkExec checkExec}
 305      *          method doesn't allow creation of the subprocess
 306      *
 307      * @throws  IOException
 308      *          If an I/O error occurs
 309      *
 310      * @throws  NullPointerException
 311      *          If {@code command} is {@code null}
 312      *
 313      * @throws  IllegalArgumentException
 314      *          If {@code command} is empty
 315      *
 316      * @see     #exec(String[], String[], File)
 317      * @see     ProcessBuilder
 318      */
 319     public Process exec(String command) throws IOException {
 320         return exec(command, null, null);
 321     }
 322 
 323     /**
 324      * Executes the specified string command in a separate process with the
 325      * specified environment.
 326      *
 327      * <p>This is a convenience method.  An invocation of the form
 328      * {@code exec(command, envp)}
 329      * behaves in exactly the same way as the invocation
 330      * {@link #exec(String, String[], File) exec}{@code (command, envp, null)}.
 331      *
 332      * @param   command   a specified system command.
 333      *
 334      * @param   envp      array of strings, each element of which
 335      *                    has environment variable settings in the format
 336      *                    <i>name</i>=<i>value</i>, or
 337      *                    {@code null} if the subprocess should inherit
 338      *                    the environment of the current process.
 339      *
 340      * @return  A new {@link Process} object for managing the subprocess
 341      *
 342      * @throws  SecurityException
 343      *          If a security manager exists and its
 344      *          {@link SecurityManager#checkExec checkExec}
 345      *          method doesn't allow creation of the subprocess
 346      *
 347      * @throws  IOException
 348      *          If an I/O error occurs
 349      *
 350      * @throws  NullPointerException
 351      *          If {@code command} is {@code null},
 352      *          or one of the elements of {@code envp} is {@code null}
 353      *
 354      * @throws  IllegalArgumentException
 355      *          If {@code command} is empty
 356      *
 357      * @see     #exec(String[], String[], File)
 358      * @see     ProcessBuilder
 359      */
 360     public Process exec(String command, String[] envp) throws IOException {
 361         return exec(command, envp, null);
 362     }
 363 
 364     /**
 365      * Executes the specified string command in a separate process with the
 366      * specified environment and working directory.
 367      *
 368      * <p>This is a convenience method.  An invocation of the form
 369      * {@code exec(command, envp, dir)}
 370      * behaves in exactly the same way as the invocation
 371      * {@link #exec(String[], String[], File) exec}{@code (cmdarray, envp, dir)},
 372      * where {@code cmdarray} is an array of all the tokens in
 373      * {@code command}.
 374      *
 375      * <p>More precisely, the {@code command} string is broken
 376      * into tokens using a {@link StringTokenizer} created by the call
 377      * {@code new {@link StringTokenizer}(command)} with no
 378      * further modification of the character categories.  The tokens
 379      * produced by the tokenizer are then placed in the new string
 380      * array {@code cmdarray}, in the same order.
 381      *
 382      * @param   command   a specified system command.
 383      *
 384      * @param   envp      array of strings, each element of which
 385      *                    has environment variable settings in the format
 386      *                    <i>name</i>=<i>value</i>, or
 387      *                    {@code null} if the subprocess should inherit
 388      *                    the environment of the current process.
 389      *
 390      * @param   dir       the working directory of the subprocess, or
 391      *                    {@code null} if the subprocess should inherit
 392      *                    the working directory of the current process.
 393      *
 394      * @return  A new {@link Process} object for managing the subprocess
 395      *
 396      * @throws  SecurityException
 397      *          If a security manager exists and its
 398      *          {@link SecurityManager#checkExec checkExec}
 399      *          method doesn't allow creation of the subprocess
 400      *
 401      * @throws  IOException
 402      *          If an I/O error occurs
 403      *
 404      * @throws  NullPointerException
 405      *          If {@code command} is {@code null},
 406      *          or one of the elements of {@code envp} is {@code null}
 407      *
 408      * @throws  IllegalArgumentException
 409      *          If {@code command} is empty
 410      *
 411      * @see     ProcessBuilder
 412      * @since 1.3
 413      */
 414     public Process exec(String command, String[] envp, File dir)
 415         throws IOException {
 416         if (command.isEmpty())
 417             throw new IllegalArgumentException("Empty command");
 418 
 419         StringTokenizer st = new StringTokenizer(command);
 420         String[] cmdarray = new String[st.countTokens()];
 421         for (int i = 0; st.hasMoreTokens(); i++)
 422             cmdarray[i] = st.nextToken();
 423         return exec(cmdarray, envp, dir);
 424     }
 425 
 426     /**
 427      * Executes the specified command and arguments in a separate process.
 428      *
 429      * <p>This is a convenience method.  An invocation of the form
 430      * {@code exec(cmdarray)}
 431      * behaves in exactly the same way as the invocation
 432      * {@link #exec(String[], String[], File) exec}{@code (cmdarray, null, null)}.
 433      *
 434      * @param   cmdarray  array containing the command to call and
 435      *                    its arguments.
 436      *
 437      * @return  A new {@link Process} object for managing the subprocess
 438      *
 439      * @throws  SecurityException
 440      *          If a security manager exists and its
 441      *          {@link SecurityManager#checkExec checkExec}
 442      *          method doesn't allow creation of the subprocess
 443      *
 444      * @throws  IOException
 445      *          If an I/O error occurs
 446      *
 447      * @throws  NullPointerException
 448      *          If {@code cmdarray} is {@code null},
 449      *          or one of the elements of {@code cmdarray} is {@code null}
 450      *
 451      * @throws  IndexOutOfBoundsException
 452      *          If {@code cmdarray} is an empty array
 453      *          (has length {@code 0})
 454      *
 455      * @see     ProcessBuilder
 456      */
 457     public Process exec(String cmdarray[]) throws IOException {
 458         return exec(cmdarray, null, null);
 459     }
 460 
 461     /**
 462      * Executes the specified command and arguments in a separate process
 463      * with the specified environment.
 464      *
 465      * <p>This is a convenience method.  An invocation of the form
 466      * {@code exec(cmdarray, envp)}
 467      * behaves in exactly the same way as the invocation
 468      * {@link #exec(String[], String[], File) exec}{@code (cmdarray, envp, null)}.
 469      *
 470      * @param   cmdarray  array containing the command to call and
 471      *                    its arguments.
 472      *
 473      * @param   envp      array of strings, each element of which
 474      *                    has environment variable settings in the format
 475      *                    <i>name</i>=<i>value</i>, or
 476      *                    {@code null} if the subprocess should inherit
 477      *                    the environment of the current process.
 478      *
 479      * @return  A new {@link Process} object for managing the subprocess
 480      *
 481      * @throws  SecurityException
 482      *          If a security manager exists and its
 483      *          {@link SecurityManager#checkExec checkExec}
 484      *          method doesn't allow creation of the subprocess
 485      *
 486      * @throws  IOException
 487      *          If an I/O error occurs
 488      *
 489      * @throws  NullPointerException
 490      *          If {@code cmdarray} is {@code null},
 491      *          or one of the elements of {@code cmdarray} is {@code null},
 492      *          or one of the elements of {@code envp} is {@code null}
 493      *
 494      * @throws  IndexOutOfBoundsException
 495      *          If {@code cmdarray} is an empty array
 496      *          (has length {@code 0})
 497      *
 498      * @see     ProcessBuilder
 499      */
 500     public Process exec(String[] cmdarray, String[] envp) throws IOException {
 501         return exec(cmdarray, envp, null);
 502     }
 503 
 504 
 505     /**
 506      * Executes the specified command and arguments in a separate process with
 507      * the specified environment and working directory.
 508      *
 509      * <p>Given an array of strings {@code cmdarray}, representing the
 510      * tokens of a command line, and an array of strings {@code envp},
 511      * representing "environment" variable settings, this method creates
 512      * a new process in which to execute the specified command.
 513      *
 514      * <p>This method checks that {@code cmdarray} is a valid operating
 515      * system command.  Which commands are valid is system-dependent,
 516      * but at the very least the command must be a non-empty list of
 517      * non-null strings.
 518      *
 519      * <p>If {@code envp} is {@code null}, the subprocess inherits the
 520      * environment settings of the current process.
 521      *
 522      * <p>A minimal set of system dependent environment variables may
 523      * be required to start a process on some operating systems.
 524      * As a result, the subprocess may inherit additional environment variable
 525      * settings beyond those in the specified environment.
 526      *
 527      * <p>{@link ProcessBuilder#start()} is now the preferred way to
 528      * start a process with a modified environment.
 529      *
 530      * <p>The working directory of the new subprocess is specified by {@code dir}.
 531      * If {@code dir} is {@code null}, the subprocess inherits the
 532      * current working directory of the current process.
 533      *
 534      * <p>If a security manager exists, its
 535      * {@link SecurityManager#checkExec checkExec}
 536      * method is invoked with the first component of the array
 537      * {@code cmdarray} as its argument. This may result in a
 538      * {@link SecurityException} being thrown.
 539      *
 540      * <p>Starting an operating system process is highly system-dependent.
 541      * Among the many things that can go wrong are:
 542      * <ul>
 543      * <li>The operating system program file was not found.
 544      * <li>Access to the program file was denied.
 545      * <li>The working directory does not exist.
 546      * </ul>
 547      *
 548      * <p>In such cases an exception will be thrown.  The exact nature
 549      * of the exception is system-dependent, but it will always be a
 550      * subclass of {@link IOException}.
 551      *
 552      * <p>If the operating system does not support the creation of
 553      * processes, an {@link UnsupportedOperationException} will be thrown.
 554      *
 555      *
 556      * @param   cmdarray  array containing the command to call and
 557      *                    its arguments.
 558      *
 559      * @param   envp      array of strings, each element of which
 560      *                    has environment variable settings in the format
 561      *                    <i>name</i>=<i>value</i>, or
 562      *                    {@code null} if the subprocess should inherit
 563      *                    the environment of the current process.
 564      *
 565      * @param   dir       the working directory of the subprocess, or
 566      *                    {@code null} if the subprocess should inherit
 567      *                    the working directory of the current process.
 568      *
 569      * @return  A new {@link Process} object for managing the subprocess
 570      *
 571      * @throws  SecurityException
 572      *          If a security manager exists and its
 573      *          {@link SecurityManager#checkExec checkExec}
 574      *          method doesn't allow creation of the subprocess
 575      *
 576      * @throws  UnsupportedOperationException
 577      *          If the operating system does not support the creation of processes.
 578      *
 579      * @throws  IOException
 580      *          If an I/O error occurs
 581      *
 582      * @throws  NullPointerException
 583      *          If {@code cmdarray} is {@code null},
 584      *          or one of the elements of {@code cmdarray} is {@code null},
 585      *          or one of the elements of {@code envp} is {@code null}
 586      *
 587      * @throws  IndexOutOfBoundsException
 588      *          If {@code cmdarray} is an empty array
 589      *          (has length {@code 0})
 590      *
 591      * @see     ProcessBuilder
 592      * @since 1.3
 593      */
 594     public Process exec(String[] cmdarray, String[] envp, File dir)
 595         throws IOException {
 596         return new ProcessBuilder(cmdarray)
 597             .environment(envp)
 598             .directory(dir)
 599             .start();
 600     }
 601 
 602     /**
 603      * Returns the number of processors available to the Java virtual machine.
 604      *
 605      * <p> This value may change during a particular invocation of the virtual
 606      * machine.  Applications that are sensitive to the number of available
 607      * processors should therefore occasionally poll this property and adjust
 608      * their resource usage appropriately. </p>
 609      *
 610      * @return  the maximum number of processors available to the virtual
 611      *          machine; never smaller than one
 612      * @since 1.4
 613      */
 614     public native int availableProcessors();
 615 
 616     /**
 617      * Returns the amount of free memory in the Java Virtual Machine.
 618      * Calling the
 619      * {@code gc} method may result in increasing the value returned
 620      * by {@code freeMemory.}
 621      *
 622      * @return  an approximation to the total amount of memory currently
 623      *          available for future allocated objects, measured in bytes.
 624      */
 625     public native long freeMemory();
 626 
 627     /**
 628      * Returns the total amount of memory in the Java virtual machine.
 629      * The value returned by this method may vary over time, depending on
 630      * the host environment.
 631      * <p>
 632      * Note that the amount of memory required to hold an object of any
 633      * given type may be implementation-dependent.
 634      *
 635      * @return  the total amount of memory currently available for current
 636      *          and future objects, measured in bytes.
 637      */
 638     public native long totalMemory();
 639 
 640     /**
 641      * Returns the maximum amount of memory that the Java virtual machine
 642      * will attempt to use.  If there is no inherent limit then the value
 643      * {@link java.lang.Long#MAX_VALUE} will be returned.
 644      *
 645      * @return  the maximum amount of memory that the virtual machine will
 646      *          attempt to use, measured in bytes
 647      * @since 1.4
 648      */
 649     public native long maxMemory();
 650 
 651     /**
 652      * Runs the garbage collector in the Java Virtual Machine.
 653      * <p>
 654      * Calling this method suggests that the Java Virtual Machine
 655      * expend effort toward recycling unused objects in order to
 656      * make the memory they currently occupy available for reuse
 657      * by the Java Virtual Machine.
 658      * When control returns from the method call, the Java Virtual Machine
 659      * has made a best effort to reclaim space from all unused objects.
 660      * There is no guarantee that this effort will recycle any particular
 661      * number of unused objects, reclaim any particular amount of space, or
 662      * complete at any particular time, if at all, before the method returns or ever.
 663      * <p>
 664      * The name {@code gc} stands for "garbage
 665      * collector". The Java Virtual Machine performs this recycling
 666      * process automatically as needed, in a separate thread, even if the
 667      * {@code gc} method is not invoked explicitly.
 668      * <p>
 669      * The method {@link System#gc()} is the conventional and convenient
 670      * means of invoking this method.
 671      */
 672     public native void gc();
 673 
 674     /**
 675      * Runs the finalization methods of any objects pending finalization.
 676      * Calling this method suggests that the Java virtual machine expend
 677      * effort toward running the {@code finalize} methods of objects
 678      * that have been found to be discarded but whose {@code finalize}
 679      * methods have not yet been run. When control returns from the
 680      * method call, the virtual machine has made a best effort to
 681      * complete all outstanding finalizations.
 682      * <p>
 683      * The virtual machine performs the finalization process
 684      * automatically as needed, in a separate thread, if the
 685      * {@code runFinalization} method is not invoked explicitly.
 686      * <p>
 687      * The method {@link System#runFinalization()} is the conventional
 688      * and convenient means of invoking this method.
 689      *
 690      * @see     java.lang.Object#finalize()
 691      */
 692     public void runFinalization() {
 693         SharedSecrets.getJavaLangRefAccess().runFinalization();
 694     }
 695 
 696     /**
 697      * Loads the native library specified by the filename argument.  The filename
 698      * argument must be an absolute path name.
 699      * (for example
 700      * {@code Runtime.getRuntime().load("/home/avh/lib/libX11.so");}).
 701      *
 702      * If the filename argument, when stripped of any platform-specific library
 703      * prefix, path, and file extension, indicates a library whose name is,
 704      * for example, L, and a native library called L is statically linked
 705      * with the VM, then the JNI_OnLoad_L function exported by the library
 706      * is invoked rather than attempting to load a dynamic library.
 707      * A filename matching the argument does not have to exist in the file
 708      * system.
 709      * See the <a href="{@docRoot}/../specs/jni/index.html"> JNI Specification</a>
 710      * for more details.
 711      *
 712      * Otherwise, the filename argument is mapped to a native library image in
 713      * an implementation-dependent manner.
 714      * <p>
 715      * First, if there is a security manager, its {@code checkLink}
 716      * method is called with the {@code filename} as its argument.
 717      * This may result in a security exception.
 718      * <p>
 719      * This is similar to the method {@link #loadLibrary(String)}, but it
 720      * accepts a general file name as an argument rather than just a library
 721      * name, allowing any file of native code to be loaded.
 722      * <p>
 723      * The method {@link System#load(String)} is the conventional and
 724      * convenient means of invoking this method.
 725      *
 726      * @param      filename   the file to load.
 727      * @throws     SecurityException  if a security manager exists and its
 728      *             {@code checkLink} method doesn't allow
 729      *             loading of the specified dynamic library
 730      * @throws     UnsatisfiedLinkError  if either the filename is not an
 731      *             absolute path name, the native library is not statically
 732      *             linked with the VM, or the library cannot be mapped to
 733      *             a native library image by the host system.
 734      * @throws     NullPointerException if {@code filename} is
 735      *             {@code null}
 736      * @see        java.lang.Runtime#getRuntime()
 737      * @see        java.lang.SecurityException
 738      * @see        java.lang.SecurityManager#checkLink(java.lang.String)
 739      */
 740     @CallerSensitive
 741     public void load(String filename) {
 742         load0(Reflection.getCallerClass(), filename);
 743     }
 744 
 745     void load0(Class<?> fromClass, String filename) {
 746         SecurityManager security = System.getSecurityManager();
 747         if (security != null) {
 748             security.checkLink(filename);
 749         }
 750         File file = new File(filename);
 751         if (!file.isAbsolute()) {
 752             throw new UnsatisfiedLinkError(
 753                 "Expecting an absolute path of the library: " + filename);
 754         }
 755         ClassLoader.loadLibrary(fromClass, file);
 756     }
 757 
 758     /**
 759      * Loads the native library specified by the {@code libname}
 760      * argument.  The {@code libname} argument must not contain any platform
 761      * specific prefix, file extension or path. If a native library
 762      * called {@code libname} is statically linked with the VM, then the
 763      * JNI_OnLoad_{@code libname} function exported by the library is invoked.
 764      * See the <a href="{@docRoot}/../specs/jni/index.html"> JNI Specification</a>
 765      * for more details.
 766      *
 767      * Otherwise, the libname argument is loaded from a system library
 768      * location and mapped to a native library image in an
 769      * implementation-dependent manner.
 770      * <p>
 771      * First, if there is a security manager, its {@code checkLink}
 772      * method is called with the {@code libname} as its argument.
 773      * This may result in a security exception.
 774      * <p>
 775      * The method {@link System#loadLibrary(String)} is the conventional
 776      * and convenient means of invoking this method. If native
 777      * methods are to be used in the implementation of a class, a standard
 778      * strategy is to put the native code in a library file (call it
 779      * {@code LibFile}) and then to put a static initializer:
 780      * <blockquote><pre>
 781      * static { System.loadLibrary("LibFile"); }
 782      * </pre></blockquote>
 783      * within the class declaration. When the class is loaded and
 784      * initialized, the necessary native code implementation for the native
 785      * methods will then be loaded as well.
 786      * <p>
 787      * If this method is called more than once with the same library
 788      * name, the second and subsequent calls are ignored.
 789      *
 790      * @param      libname   the name of the library.
 791      * @throws     SecurityException  if a security manager exists and its
 792      *             {@code checkLink} method doesn't allow
 793      *             loading of the specified dynamic library
 794      * @throws     UnsatisfiedLinkError if either the libname argument
 795      *             contains a file path, the native library is not statically
 796      *             linked with the VM,  or the library cannot be mapped to a
 797      *             native library image by the host system.
 798      * @throws     NullPointerException if {@code libname} is
 799      *             {@code null}
 800      * @see        java.lang.SecurityException
 801      * @see        java.lang.SecurityManager#checkLink(java.lang.String)
 802      */
 803     @CallerSensitive
 804     public void loadLibrary(String libname) {
 805         loadLibrary0(Reflection.getCallerClass(), libname);
 806     }
 807 
 808     void loadLibrary0(Class<?> fromClass, String libname) {
 809         SecurityManager security = System.getSecurityManager();
 810         if (security != null) {
 811             security.checkLink(libname);
 812         }
 813         if (libname.indexOf((int)File.separatorChar) != -1) {
 814             throw new UnsatisfiedLinkError(
 815                 "Directory separator should not appear in library name: " + libname);
 816         }
 817         ClassLoader.loadLibrary(fromClass, libname);
 818     }
 819 
 820     /**
 821      * Returns the implementation-specific estimate of the amount of storage
 822      * consumed by the specified object.
 823      * <p>
 824      * The estimate may change during a single invocation of the JVM. JVM may
 825      * answer the "don't know" value if it does not know the size of the object.
 826      * JVM may answer the "don't know" value if it refuses to provide the estimate.
 827      *
 828      * @param obj object to estimate the size of
 829      * @return storage size in bytes, or {@code -1} if storage size is unknown
 830      * @throws NullPointerException if {@code obj} is {@code null}
 831      * @since 16
 832      */
 833     @DontInline // Semantics: make sure the object is not scalar replaced.
 834     public static long sizeOf(Object obj) {
 835         Objects.requireNonNull(obj);
 836         return sizeOf0(obj);
 837     }
 838 
 839     @HotSpotIntrinsicCandidate
 840     private static native long sizeOf0(Object obj);
 841 
 842     /**
 843      * Bit value for {@link #deepSizeOf(Object, ToLongFunction)}'s callback
 844      * return value to continue traversal ("go deep") of the references of
 845      * the object passed to the callback.
 846      */
 847     public static final long DEEP_SIZE_OF_TRAVERSE = 1;
 848     /**
 849      * Bit value for {@link #deepSizeOf(Object, ToLongFunction)}'s callback
 850      * return value to consider the shallow size of the object passed to the
 851      * callback.
 852      */
 853     public static final long DEEP_SIZE_OF_SHALLOW = 2;
 854 
 855     /**
 856      * Returns the implementation-specific estimate of the amount of storage
 857      * consumed by the specified object and all objects referenced by it.
 858      * <p>
 859      * The estimate may change during a single invocation of the JVM. Notably,
 860      * the estimate is not guaranteed to remain stable if the object references in
 861      * the walked subgraph change when {@code deepSizeOf} is running.
 862      * <p>
 863      * JVM may answer the "don't know" value if it does not know the size of the
 864      * specified object or any of objects referenced from it. JVM may answer
 865      * "don't know" value if it refuses to provide the estimate.
 866      *
 867      * @param obj root object to start the estimate from
 868      * @return storage size in bytes, or {@code -1} if storage size is unknown
 869      * @throws NullPointerException if {@code obj} is {@code null}
 870      * @since 16
 871      */
 872     public static long deepSizeOf(Object obj) {
 873         return deepSizeOf(obj, (o) -> DEEP_SIZE_OF_TRAVERSE | DEEP_SIZE_OF_SHALLOW);
 874     }
 875 
 876     private static long handleIncludeCheck(ArrayDeque<Object> q, Object o, ToLongFunction<Object> ic, long ts, long os) {
 877         long t = ic.applyAsLong(o);
 878         if (t > 0) {
 879             if ((t & DEEP_SIZE_OF_TRAVERSE) != 0) {
 880                 q.push(o);
 881             }
 882             if ((t & DEEP_SIZE_OF_SHALLOW) != 0) {
 883                 ts += os;
 884             }
 885         } else {
 886             ts -= t;
 887         }
 888         return ts;
 889     }
 890 
 891     /**
 892      * Returns the implementation-specific estimate of the amount of storage
 893      * consumed by the specified object and all objects referenced by it.
 894      * <p>
 895      * The estimate may change during a single invocation of the JVM. Notably,
 896      * the estimate is not guaranteed to remain stable if the object references in
 897      * the walked subgraph change when {@code deepSizeOf} is running.
 898      * <p>
 899      * JVM may answer the "don't know" value if it does not know the size of the
 900      * specified object or any of objects referenced from it. JVM may answer
 901      * "don't know" value if it refuses to provide the estimate.
 902      *
 903      * @param obj root object to start the estimate from
 904      * @param includeCheck callback to evaluate an object's size. The callback can
 905      * return a positive value as a bitmask - valid values are
 906      * {@link #DEEP_SIZE_OF_SHALLOW} to consider the object's shallow sise and
 907      * {@link #DEEP_SIZE_OF_TRAVERSE} to traverse ("go deeper") the object's
 908      * references. A negative value means that the absolute return value is
 909      * considered and the object's references are not considered.
 910      * @return storage size in bytes, or {@code -1} if storage size is unknown
 911      * @throws NullPointerException if {@code obj} is {@code null}
 912      * @since 16
 913      */
 914     @DontInline // Semantics: make sure the object is not scalar replaced.
 915     public static long deepSizeOf(Object obj, ToLongFunction<Object> includeCheck) {
 916         Objects.requireNonNull(obj);
 917 
 918         // We are potentially leaking the objects to includeCheck callback.
 919         // These objects are peeled from the private fields as well, which
 920         // circumvents the normal Java access rules. Check we have the privilege.
 921         SecurityManager sm = System.getSecurityManager();
 922         if (sm != null) {
 923             sm.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 924         }
 925 
 926         long rootSize = sizeOf0(obj);
 927         if (rootSize < 0) {
 928             return rootSize;
 929         }
 930 
 931         IdentityHashSet visited = new IdentityHashSet(IdentityHashSet.MINIMUM_CAPACITY);
 932         ArrayDeque<Object> q = new ArrayDeque<>();
 933 
 934         visited.add(obj);
 935         long totalSize = handleIncludeCheck(q, obj, includeCheck, 0, rootSize);
 936 
 937         Object[] refBuf = new Object[1];
 938 
 939         while (!q.isEmpty()) {
 940             Object o = q.pop();
 941             Class<?> cl = o.getClass();
 942             if (cl.isArray()) {
 943                 // Separate array path avoids adding a lot of (potentially large) array
 944                 // contents on the queue. No need to handle primitive arrays too.
 945 
 946                 if (cl.getComponentType().isPrimitive()) {
 947                     continue;
 948                 }
 949 
 950                 for (Object e : (Object[])o) {
 951                     if (e != null && visited.add(e)) {
 952                         long size = sizeOf0(e);
 953                         if (size < 0) {
 954                             return size;
 955                         }
 956                         totalSize = handleIncludeCheck(q, e, includeCheck, totalSize, size);
 957                     }
 958                 }
 959             } else {
 960                 int objs;
 961                 while ((objs = getReferencedObjects(o, refBuf)) < 0) {
 962                     refBuf = new Object[refBuf.length * 2];
 963                 }
 964 
 965                 for (int c = 0; c < objs; c++) {
 966                     Object e = refBuf[c];
 967                     if (visited.add(e)) {
 968                         long size = sizeOf0(e);
 969                         if (size < 0) {
 970                             return size;
 971                         }
 972                         totalSize = handleIncludeCheck(q, e, includeCheck, totalSize, size);
 973                     }
 974                 }
 975 
 976                 // Null out the buffer: do not keep these objects referenced until next
 977                 // buffer fill, and help the VM code to avoid full SATB barriers on existing
 978                 // buffer elements in getReferencedObjects.
 979                 Arrays.fill(refBuf, 0, objs, null);
 980             }
 981         }
 982 
 983         return totalSize;
 984     }
 985 
 986     /**
 987      * Peels the referenced objects from the given object and puts them
 988      * into the reference buffer. Never returns nulls in reference buffer.
 989      * Returns the number of valid elements in the buffer. If reference bufffer
 990      * is too small, returns -1.
 991      *
 992      * @param obj object to peel
 993      * @param refBuf reference buffer
 994      * @return number of valid elements in buffer, -1 if buffer is too small
 995      */
 996     @HotSpotIntrinsicCandidate
 997     private static native int getReferencedObjects(Object obj, Object[] refBuf);
 998 
 999     private static final class IdentityHashSet {
1000         private static final int MINIMUM_CAPACITY = 4;
1001         private static final int MAXIMUM_CAPACITY = 1 << 29;
1002 
1003         private Object[] table;
1004         private int size;
1005 
1006         public IdentityHashSet(int expectedMaxSize) {
1007             table = new Object[capacity(expectedMaxSize)];
1008         }
1009 
1010         private static int capacity(int expectedMaxSize) {
1011             return
1012                 (expectedMaxSize > MAXIMUM_CAPACITY / 3) ? MAXIMUM_CAPACITY :
1013                 (expectedMaxSize <= 2 * MINIMUM_CAPACITY / 3) ? MINIMUM_CAPACITY :
1014                 Integer.highestOneBit(expectedMaxSize + (expectedMaxSize << 1));
1015         }
1016 
1017         private static int nextIndex(int i, int len) {
1018             return (i + 1 < len ? i + 1 : 0);
1019         }
1020 
1021         public boolean add(Object o) {
1022             while (true) {
1023                 final Object[] tab = table;
1024                 final int len = tab.length;
1025                 int i = System.identityHashCode(o) & (len - 1);
1026 
1027                 for (Object item; (item = tab[i]) != null; i = nextIndex(i, len)) {
1028                     if (item == o) {
1029                         return false;
1030                     }
1031                 }
1032 
1033                 final int s = size + 1;
1034                 if (s*3 > len && resize()) continue;
1035 
1036                 tab[i] = o;
1037                 size = s;
1038                 return true;
1039             }
1040         }
1041 
1042         private boolean resize() {
1043             Object[] oldTable = table;
1044             int oldLength = oldTable.length;
1045             if (oldLength == MAXIMUM_CAPACITY) {
1046                 throw new IllegalStateException("Capacity exhausted.");
1047             }
1048 
1049             int newLength = oldLength * 2;
1050             if (newLength <= oldLength) {
1051                 return false;
1052             }
1053 
1054             Object[] newTable = new Object[newLength];
1055             for (Object o : oldTable) {
1056                 if (o != null) {
1057                     int i = System.identityHashCode(o) & (newLength - 1);
1058                     while (newTable[i] != null) {
1059                         i = nextIndex(i, newLength);
1060                     }
1061                     newTable[i] = o;
1062                 }
1063             }
1064             table = newTable;
1065             return true;
1066         }
1067     }
1068 
1069     /**
1070      * Returns the implementation-specific representation of the memory address
1071      * where the specified object resides.
1072      * <p>
1073      * The estimate may change during a single invocation of the JVM. Notably,
1074      * in the presence of moving garbage collector, the address can change at any
1075      * time, including during the call. As such, this method is only useful for
1076      * low-level debugging and heap introspection in a quiescent application.
1077      * <p>
1078      * JVM may answer the "don't know" value if it does not know the address of
1079      * the specified object, or refuses to provide this information.
1080      *
1081      * @param obj object to get the address of
1082      * @return current object address, or "0" if {@code obj} is @{code null},
1083      *         or {@code -1} if address is unknown
1084      * @since 16
1085      */
1086     @DontInline // Semantics: make sure the object is not scalar replaced.
1087     public static long addressOf(Object obj) {
1088         return addressOf0(obj);
1089     }
1090 
1091     @HotSpotIntrinsicCandidate
1092     private static native long addressOf0(Object obj);
1093 
1094     /**
1095      * Returns the implementation-specific estimate of the offset of the field
1096      * within the holding container.
1097      * <p>
1098      * For the instance fields, the offset is from the beginning of the holder
1099      * object. For the static fields, the offset is from the beginning of the
1100      * unspecified holder area. As such, these offsets are useful for comparing
1101      * the offsets of two fields, not for any kind of absolute addressing.
1102      * <p>
1103      * The estimate may change during a single invocation of the JVM, for example
1104      * during class redefinition.
1105      * <p>
1106      * JVM may answer the "don't know" value if it does not know the address of
1107      * the specified object, or refuses to provide this information.
1108      *
1109      * @param field field to poll
1110      * @return the field offset in bytes, or {@code -1} if field offset is unknown
1111      * @throws NullPointerException if {@code field} is {@code null}
1112      * @since 16
1113      */
1114     public static long fieldOffsetOf(Field field) {
1115         Objects.requireNonNull(field);
1116         return fieldOffsetOf0(field);
1117     }
1118 
1119     // Reflection-like call, is not supposed to be fast?
1120     private static native long fieldOffsetOf0(Field field);
1121 
1122     /**
1123      * Returns the implementation-specific estimate of the field slot size for
1124      * the specified object field.
1125      * <p>
1126      * The estimate may change during a single invocation of the JVM.
1127      * <p>
1128      * JVM may answer the "don't know" value if it does not know the address of
1129      * the specified object, or refuses to provide this information.
1130      *
1131      * TODO: Split by staticness?
1132      *
1133      * @param field field to poll
1134      * @return the field size in bytes, or {@code -1} if field size is unknown
1135      * @throws NullPointerException if {@code field} is {@code null}
1136      * @since 16
1137      */
1138     public static long fieldSizeOf(Field field) {
1139         Objects.requireNonNull(field);
1140         return fieldSizeOf0(field);
1141     }
1142 
1143     // Reflection-like call, is not supposed to be fast?
1144     private static native long fieldSizeOf0(Field field);
1145 
1146     /**
1147      * Returns the version of the Java Runtime Environment as a {@link Version}.
1148      *
1149      * @return  the {@link Version} of the Java Runtime Environment
1150      *
1151      * @since  9
1152      */
1153     public static Version version() {
1154         if (version == null) {
1155             version = new Version(VersionProps.versionNumbers(),
1156                     VersionProps.pre(), VersionProps.build(),
1157                     VersionProps.optional());
1158         }
1159         return version;
1160     }
1161 
1162     /**
1163      * A representation of a version string for an implementation of the
1164      * Java&nbsp;SE Platform.  A version string consists of a version number
1165      * optionally followed by pre-release and build information.
1166      *
1167      * <h2><a id="verNum">Version numbers</a></h2>
1168      *
1169      * <p> A <em>version number</em>, {@code $VNUM}, is a non-empty sequence of
1170      * elements separated by period characters (U+002E).  An element is either
1171      * zero, or an unsigned integer numeral without leading zeros.  The final
1172      * element in a version number must not be zero.  When an element is
1173      * incremented, all subsequent elements are removed.  The format is: </p>
1174      *
1175      * <blockquote><pre>
1176      * [1-9][0-9]*((\.0)*\.[1-9][0-9]*)*
1177      * </pre></blockquote>
1178      *
1179      * <p> The sequence may be of arbitrary length but the first four elements
1180      * are assigned specific meanings, as follows:</p>
1181      *
1182      * <blockquote><pre>
1183      * $FEATURE.$INTERIM.$UPDATE.$PATCH
1184      * </pre></blockquote>
1185      *
1186      * <ul>
1187      *
1188      * <li><p> <a id="FEATURE">{@code $FEATURE}</a> — The
1189      * feature-release counter, incremented for every feature release
1190      * regardless of release content.  Features may be added in a feature
1191      * release; they may also be removed, if advance notice was given at least
1192      * one feature release ahead of time.  Incompatible changes may be made
1193      * when justified. </p></li>
1194      *
1195      * <li><p> <a id="INTERIM">{@code $INTERIM}</a> — The
1196      * interim-release counter, incremented for non-feature releases that
1197      * contain compatible bug fixes and enhancements but no incompatible
1198      * changes, no feature removals, and no changes to standard APIs.
1199      * </p></li>
1200      *
1201      * <li><p> <a id="UPDATE">{@code $UPDATE}</a> — The update-release
1202      * counter, incremented for compatible update releases that fix security
1203      * issues, regressions, and bugs in newer features. </p></li>
1204      *
1205      * <li><p> <a id="PATCH">{@code $PATCH}</a> — The emergency
1206      * patch-release counter, incremented only when it's necessary to produce
1207      * an emergency release to fix a critical issue. </p></li>
1208      *
1209      * </ul>
1210      *
1211      * <p> The fifth and later elements of a version number are free for use by
1212      * platform implementors, to identify implementor-specific patch
1213      * releases. </p>
1214      *
1215      * <p> A version number never has trailing zero elements.  If an element
1216      * and all those that follow it logically have the value zero then all of
1217      * them are omitted. </p>
1218      *
1219      * <p> The sequence of numerals in a version number is compared to another
1220      * such sequence in numerical, pointwise fashion; <em>e.g.</em>, {@code
1221      * 10.0.4} is less than {@code 10.1.2}.  If one sequence is shorter than
1222      * another then the missing elements of the shorter sequence are considered
1223      * to be less than the corresponding elements of the longer sequence;
1224      * <em>e.g.</em>, {@code 10.0.2} is less than {@code 10.0.2.1}. </p>
1225      *
1226      * <h2><a id="verStr">Version strings</a></h2>
1227      *
1228      * <p> A <em>version string</em>, {@code $VSTR}, is a version number {@code
1229      * $VNUM}, as described above, optionally followed by pre-release and build
1230      * information, in one of the following formats: </p>
1231      *
1232      * <blockquote><pre>
1233      *     $VNUM(-$PRE)?\+$BUILD(-$OPT)?
1234      *     $VNUM-$PRE(-$OPT)?
1235      *     $VNUM(\+-$OPT)?
1236      * </pre></blockquote>
1237      *
1238      * <p> where: </p>
1239      *
1240      * <ul>
1241      *
1242      * <li><p> <a id="pre">{@code $PRE}</a>, matching {@code ([a-zA-Z0-9]+)}
1243      * — A pre-release identifier.  Typically {@code ea}, for a
1244      * potentially unstable early-access release under active development, or
1245      * {@code internal}, for an internal developer build. </p></li>
1246      *
1247      * <li><p> <a id="build">{@code $BUILD}</a>, matching {@code
1248      * (0|[1-9][0-9]*)} — The build number, incremented for each promoted
1249      * build.  {@code $BUILD} is reset to {@code 1} when any portion of {@code
1250      * $VNUM} is incremented. </p></li>
1251      *
1252      * <li><p> <a id="opt">{@code $OPT}</a>, matching {@code ([-a-zA-Z0-9.]+)}
1253      * — Additional build information, if desired.  In the case of an
1254      * {@code internal} build this will often contain the date and time of the
1255      * build. </p></li>
1256      *
1257      * </ul>
1258      *
1259      * <p> A version string {@code 10-ea} matches {@code $VNUM = "10"} and
1260      * {@code $PRE = "ea"}.  The version string {@code 10+-ea} matches
1261      * {@code $VNUM = "10"} and {@code $OPT = "ea"}. </p>
1262      *
1263      * <p> When comparing two version strings, the value of {@code $OPT}, if
1264      * present, may or may not be significant depending on the chosen
1265      * comparison method.  The comparison methods {@link #compareTo(Version)
1266      * compareTo()} and {@link #compareToIgnoreOptional(Version)
1267      * compareToIgnoreOptional()} should be used consistently with the
1268      * corresponding methods {@link #equals(Object) equals()} and {@link
1269      * #equalsIgnoreOptional(Object) equalsIgnoreOptional()}.  </p>
1270      *
1271      * <p> A <em>short version string</em>, {@code $SVSTR}, often useful in
1272      * less formal contexts, is a version number optionally followed by a
1273      * pre-release identifier:</p>
1274      *
1275      * <blockquote><pre>
1276      *     $VNUM(-$PRE)?
1277      * </pre></blockquote>
1278      *
1279      * <p>This is a <a href="./doc-files/ValueBased.html">value-based</a>
1280      * class; use of identity-sensitive operations (including reference equality
1281      * ({@code ==}), identity hash code, or synchronization) on instances of
1282      * {@code Version} may have unpredictable results and should be avoided.
1283      * </p>
1284      *
1285      * @since  9
1286      */
1287     public static final class Version
1288         implements Comparable<Version>
1289     {
1290         private final List<Integer>     version;
1291         private final Optional<String>  pre;
1292         private final Optional<Integer> build;
1293         private final Optional<String>  optional;
1294 
1295         /*
1296          * List of version number components passed to this constructor MUST
1297          * be at least unmodifiable (ideally immutable). In the case of an
1298          * unmodifiable list, the caller MUST hand the list over to this
1299          * constructor and never change the underlying list.
1300          */
1301         private Version(List<Integer> unmodifiableListOfVersions,
1302                         Optional<String> pre,
1303                         Optional<Integer> build,
1304                         Optional<String> optional)
1305         {
1306             this.version = unmodifiableListOfVersions;
1307             this.pre = pre;
1308             this.build = build;
1309             this.optional = optional;
1310         }
1311 
1312         /**
1313          * Parses the given string as a valid
1314          * <a href="#verStr">version string</a> containing a
1315          * <a href="#verNum">version number</a> followed by pre-release and
1316          * build information.
1317          *
1318          * @param  s
1319          *         A string to interpret as a version
1320          *
1321          * @throws  IllegalArgumentException
1322          *          If the given string cannot be interpreted as a valid
1323          *          version
1324          *
1325          * @throws  NullPointerException
1326          *          If the given string is {@code null}
1327          *
1328          * @throws  NumberFormatException
1329          *          If an element of the version number or the build number
1330          *          cannot be represented as an {@link Integer}
1331          *
1332          * @return  The Version of the given string
1333          */
1334         public static Version parse(String s) {
1335             if (s == null)
1336                 throw new NullPointerException();
1337 
1338             // Shortcut to avoid initializing VersionPattern when creating
1339             // feature-version constants during startup
1340             if (isSimpleNumber(s)) {
1341                 return new Version(List.of(Integer.parseInt(s)),
1342                         Optional.empty(), Optional.empty(), Optional.empty());
1343             }
1344             Matcher m = VersionPattern.VSTR_PATTERN.matcher(s);
1345             if (!m.matches())
1346                 throw new IllegalArgumentException("Invalid version string: '"
1347                                                    + s + "'");
1348 
1349             // $VNUM is a dot-separated list of integers of arbitrary length
1350             String[] split = m.group(VersionPattern.VNUM_GROUP).split("\\.");
1351             Integer[] version = new Integer[split.length];
1352             for (int i = 0; i < split.length; i++) {
1353                 version[i] = Integer.parseInt(split[i]);
1354             }
1355 
1356             Optional<String> pre = Optional.ofNullable(
1357                     m.group(VersionPattern.PRE_GROUP));
1358 
1359             String b = m.group(VersionPattern.BUILD_GROUP);
1360             // $BUILD is an integer
1361             Optional<Integer> build = (b == null)
1362                 ? Optional.empty()
1363                 : Optional.of(Integer.parseInt(b));
1364 
1365             Optional<String> optional = Optional.ofNullable(
1366                     m.group(VersionPattern.OPT_GROUP));
1367 
1368             // empty '+'
1369             if (!build.isPresent()) {
1370                 if (m.group(VersionPattern.PLUS_GROUP) != null) {
1371                     if (optional.isPresent()) {
1372                         if (pre.isPresent())
1373                             throw new IllegalArgumentException("'+' found with"
1374                                 + " pre-release and optional components:'" + s
1375                                 + "'");
1376                     } else {
1377                         throw new IllegalArgumentException("'+' found with neither"
1378                             + " build or optional components: '" + s + "'");
1379                     }
1380                 } else {
1381                     if (optional.isPresent() && !pre.isPresent()) {
1382                         throw new IllegalArgumentException("optional component"
1383                             + " must be preceded by a pre-release component"
1384                             + " or '+': '" + s + "'");
1385                     }
1386                 }
1387             }
1388             return new Version(List.of(version), pre, build, optional);
1389         }
1390 
1391         private static boolean isSimpleNumber(String s) {
1392             for (int i = 0; i < s.length(); i++) {
1393                 char c = s.charAt(i);
1394                 char lowerBound = (i > 0) ? '0' : '1';
1395                 if (c < lowerBound || c > '9') {
1396                     return false;
1397                 }
1398             }
1399             return true;
1400         }
1401 
1402         /**
1403          * Returns the value of the <a href="#FEATURE">feature</a> element of
1404          * the version number.
1405          *
1406          * @return The value of the feature element
1407          *
1408          * @since 10
1409          */
1410         public int feature() {
1411             return version.get(0);
1412         }
1413 
1414         /**
1415          * Returns the value of the <a href="#INTERIM">interim</a> element of
1416          * the version number, or zero if it is absent.
1417          *
1418          * @return The value of the interim element, or zero
1419          *
1420          * @since 10
1421          */
1422         public int interim() {
1423             return (version.size() > 1 ? version.get(1) : 0);
1424         }
1425 
1426         /**
1427          * Returns the value of the <a href="#UPDATE">update</a> element of the
1428          * version number, or zero if it is absent.
1429          *
1430          * @return The value of the update element, or zero
1431          *
1432          * @since 10
1433          */
1434         public int update() {
1435             return (version.size() > 2 ? version.get(2) : 0);
1436         }
1437 
1438         /**
1439          * Returns the value of the <a href="#PATCH">patch</a> element of the
1440          * version number, or zero if it is absent.
1441          *
1442          * @return The value of the patch element, or zero
1443          *
1444          * @since 10
1445          */
1446         public int patch() {
1447             return (version.size() > 3 ? version.get(3) : 0);
1448         }
1449 
1450         /**
1451          * Returns the value of the major element of the version number.
1452          *
1453          * @deprecated As of Java&nbsp;SE 10, the first element of a version
1454          * number is not the major-release number but the feature-release
1455          * counter, incremented for every time-based release.  Use the {@link
1456          * #feature()} method in preference to this method.  For compatibility,
1457          * this method returns the value of the <a href="#FEATURE">feature</a>
1458          * element.
1459          *
1460          * @return The value of the feature element
1461          */
1462         @Deprecated(since = "10")
1463         public int major() {
1464             return feature();
1465         }
1466 
1467         /**
1468          * Returns the value of the minor element of the version number, or
1469          * zero if it is absent.
1470          *
1471          * @deprecated As of Java&nbsp;SE 10, the second element of a version
1472          * number is not the minor-release number but the interim-release
1473          * counter, incremented for every interim release.  Use the {@link
1474          * #interim()} method in preference to this method.  For compatibility,
1475          * this method returns the value of the <a href="#INTERIM">interim</a>
1476          * element, or zero if it is absent.
1477          *
1478          * @return The value of the interim element, or zero
1479          */
1480         @Deprecated(since = "10")
1481         public int minor() {
1482             return interim();
1483         }
1484 
1485         /**
1486          * Returns the value of the security element of the version number, or
1487          * zero if it is absent.
1488          *
1489          * @deprecated As of Java&nbsp;SE 10, the third element of a version
1490          * number is not the security level but the update-release counter,
1491          * incremented for every update release.  Use the {@link #update()}
1492          * method in preference to this method.  For compatibility, this method
1493          * returns the value of the <a href="#UPDATE">update</a> element, or
1494          * zero if it is absent.
1495          *
1496          * @return  The value of the update element, or zero
1497          */
1498         @Deprecated(since = "10")
1499         public int security() {
1500             return update();
1501         }
1502 
1503         /**
1504          * Returns an unmodifiable {@link java.util.List List} of the integers
1505          * represented in the <a href="#verNum">version number</a>.
1506          * The {@code List} always contains at least one element corresponding to
1507          * the <a href="#FEATURE">feature version number</a>.
1508          *
1509          * @return  An unmodifiable list of the integers
1510          *          represented in the version number
1511          */
1512         public List<Integer> version() {
1513             return version;
1514         }
1515 
1516         /**
1517          * Returns the optional <a href="#pre">pre-release</a> information.
1518          *
1519          * @return  The optional pre-release information as a String
1520          */
1521         public Optional<String> pre() {
1522             return pre;
1523         }
1524 
1525         /**
1526          * Returns the <a href="#build">build number</a>.
1527          *
1528          * @return  The optional build number.
1529          */
1530         public Optional<Integer> build() {
1531             return build;
1532         }
1533 
1534         /**
1535          * Returns <a href="#opt">optional</a> additional identifying build
1536          * information.
1537          *
1538          * @return  Additional build information as a String
1539          */
1540         public Optional<String> optional() {
1541             return optional;
1542         }
1543 
1544         /**
1545          * Compares this version to another.
1546          *
1547          * <p> Each of the components in the <a href="#verStr">version</a> is
1548          * compared in the following order of precedence: version numbers,
1549          * pre-release identifiers, build numbers, optional build information.
1550          * </p>
1551          *
1552          * <p> Comparison begins by examining the sequence of version numbers.
1553          * If one sequence is shorter than another, then the missing elements
1554          * of the shorter sequence are considered to be less than the
1555          * corresponding elements of the longer sequence. </p>
1556          *
1557          * <p> A version with a pre-release identifier is always considered to
1558          * be less than a version without one.  Pre-release identifiers are
1559          * compared numerically when they consist only of digits, and
1560          * lexicographically otherwise.  Numeric identifiers are considered to
1561          * be less than non-numeric identifiers.  </p>
1562          *
1563          * <p> A version without a build number is always less than one with a
1564          * build number; otherwise build numbers are compared numerically. </p>
1565          *
1566          * <p> The optional build information is compared lexicographically.
1567          * During this comparison, a version with optional build information is
1568          * considered to be greater than a version without one. </p>
1569          *
1570          * @param  obj
1571          *         The object to be compared
1572          *
1573          * @return  A negative integer, zero, or a positive integer if this
1574          *          {@code Version} is less than, equal to, or greater than the
1575          *          given {@code Version}
1576          *
1577          * @throws  NullPointerException
1578          *          If the given object is {@code null}
1579          */
1580         @Override
1581         public int compareTo(Version obj) {
1582             return compare(obj, false);
1583         }
1584 
1585         /**
1586          * Compares this version to another disregarding optional build
1587          * information.
1588          *
1589          * <p> Two versions are compared by examining the version string as
1590          * described in {@link #compareTo(Version)} with the exception that the
1591          * optional build information is always ignored. </p>
1592          *
1593          * <p> This method provides ordering which is consistent with
1594          * {@code equalsIgnoreOptional()}. </p>
1595          *
1596          * @param  obj
1597          *         The object to be compared
1598          *
1599          * @return  A negative integer, zero, or a positive integer if this
1600          *          {@code Version} is less than, equal to, or greater than the
1601          *          given {@code Version}
1602          *
1603          * @throws  NullPointerException
1604          *          If the given object is {@code null}
1605          */
1606         public int compareToIgnoreOptional(Version obj) {
1607             return compare(obj, true);
1608         }
1609 
1610         private int compare(Version obj, boolean ignoreOpt) {
1611             if (obj == null)
1612                 throw new NullPointerException();
1613 
1614             int ret = compareVersion(obj);
1615             if (ret != 0)
1616                 return ret;
1617 
1618             ret = comparePre(obj);
1619             if (ret != 0)
1620                 return ret;
1621 
1622             ret = compareBuild(obj);
1623             if (ret != 0)
1624                 return ret;
1625 
1626             if (!ignoreOpt)
1627                 return compareOptional(obj);
1628 
1629             return 0;
1630         }
1631 
1632         private int compareVersion(Version obj) {
1633             int size = version.size();
1634             int oSize = obj.version().size();
1635             int min = Math.min(size, oSize);
1636             for (int i = 0; i < min; i++) {
1637                 int val = version.get(i);
1638                 int oVal = obj.version().get(i);
1639                 if (val != oVal)
1640                     return val - oVal;
1641             }
1642             return size - oSize;
1643         }
1644 
1645         private int comparePre(Version obj) {
1646             Optional<String> oPre = obj.pre();
1647             if (!pre.isPresent()) {
1648                 if (oPre.isPresent())
1649                     return 1;
1650             } else {
1651                 if (!oPre.isPresent())
1652                     return -1;
1653                 String val = pre.get();
1654                 String oVal = oPre.get();
1655                 if (val.matches("\\d+")) {
1656                     return (oVal.matches("\\d+")
1657                         ? (new BigInteger(val)).compareTo(new BigInteger(oVal))
1658                         : -1);
1659                 } else {
1660                     return (oVal.matches("\\d+")
1661                         ? 1
1662                         : val.compareTo(oVal));
1663                 }
1664             }
1665             return 0;
1666         }
1667 
1668         private int compareBuild(Version obj) {
1669             Optional<Integer> oBuild = obj.build();
1670             if (oBuild.isPresent()) {
1671                 return (build.isPresent()
1672                         ? build.get().compareTo(oBuild.get())
1673                         : -1);
1674             } else if (build.isPresent()) {
1675                 return 1;
1676             }
1677             return 0;
1678         }
1679 
1680         private int compareOptional(Version obj) {
1681             Optional<String> oOpt = obj.optional();
1682             if (!optional.isPresent()) {
1683                 if (oOpt.isPresent())
1684                     return -1;
1685             } else {
1686                 if (!oOpt.isPresent())
1687                     return 1;
1688                 return optional.get().compareTo(oOpt.get());
1689             }
1690             return 0;
1691         }
1692 
1693         /**
1694          * Returns a string representation of this version.
1695          *
1696          * @return  The version string
1697          */
1698         @Override
1699         public String toString() {
1700             StringBuilder sb
1701                 = new StringBuilder(version.stream()
1702                     .map(Object::toString)
1703                     .collect(Collectors.joining(".")));
1704 
1705             pre.ifPresent(v -> sb.append("-").append(v));
1706 
1707             if (build.isPresent()) {
1708                 sb.append("+").append(build.get());
1709                 if (optional.isPresent())
1710                     sb.append("-").append(optional.get());
1711             } else {
1712                 if (optional.isPresent()) {
1713                     sb.append(pre.isPresent() ? "-" : "+-");
1714                     sb.append(optional.get());
1715                 }
1716             }
1717 
1718             return sb.toString();
1719         }
1720 
1721         /**
1722          * Determines whether this {@code Version} is equal to another object.
1723          *
1724          * <p> Two {@code Version}s are equal if and only if they represent the
1725          * same version string.
1726          *
1727          * @param  obj
1728          *         The object to which this {@code Version} is to be compared
1729          *
1730          * @return  {@code true} if, and only if, the given object is a {@code
1731          *          Version} that is identical to this {@code Version}
1732          *
1733          */
1734         @Override
1735         public boolean equals(Object obj) {
1736             boolean ret = equalsIgnoreOptional(obj);
1737             if (!ret)
1738                 return false;
1739 
1740             Version that = (Version)obj;
1741             return (this.optional().equals(that.optional()));
1742         }
1743 
1744         /**
1745          * Determines whether this {@code Version} is equal to another
1746          * disregarding optional build information.
1747          *
1748          * <p> Two {@code Version}s are equal if and only if they represent the
1749          * same version string disregarding the optional build information.
1750          *
1751          * @param  obj
1752          *         The object to which this {@code Version} is to be compared
1753          *
1754          * @return  {@code true} if, and only if, the given object is a {@code
1755          *          Version} that is identical to this {@code Version}
1756          *          ignoring the optional build information
1757          *
1758          */
1759         public boolean equalsIgnoreOptional(Object obj) {
1760             if (this == obj)
1761                 return true;
1762             if (!(obj instanceof Version))
1763                 return false;
1764 
1765             Version that = (Version)obj;
1766             return (this.version().equals(that.version())
1767                 && this.pre().equals(that.pre())
1768                 && this.build().equals(that.build()));
1769         }
1770 
1771         /**
1772          * Returns the hash code of this version.
1773          *
1774          * @return  The hashcode of this version
1775          */
1776         @Override
1777         public int hashCode() {
1778             int h = 1;
1779             int p = 17;
1780 
1781             h = p * h + version.hashCode();
1782             h = p * h + pre.hashCode();
1783             h = p * h + build.hashCode();
1784             h = p * h + optional.hashCode();
1785 
1786             return h;
1787         }
1788     }
1789 
1790     private static class VersionPattern {
1791         // $VNUM(-$PRE)?(\+($BUILD)?(\-$OPT)?)?
1792         // RE limits the format of version strings
1793         // ([1-9][0-9]*(?:(?:\.0)*\.[1-9][0-9]*)*)(?:-([a-zA-Z0-9]+))?(?:(\+)(0|[1-9][0-9]*)?)?(?:-([-a-zA-Z0-9.]+))?
1794 
1795         private static final String VNUM
1796             = "(?<VNUM>[1-9][0-9]*(?:(?:\\.0)*\\.[1-9][0-9]*)*)";
1797         private static final String PRE      = "(?:-(?<PRE>[a-zA-Z0-9]+))?";
1798         private static final String BUILD
1799             = "(?:(?<PLUS>\\+)(?<BUILD>0|[1-9][0-9]*)?)?";
1800         private static final String OPT      = "(?:-(?<OPT>[-a-zA-Z0-9.]+))?";
1801         private static final String VSTR_FORMAT = VNUM + PRE + BUILD + OPT;
1802 
1803         static final Pattern VSTR_PATTERN = Pattern.compile(VSTR_FORMAT);
1804 
1805         static final String VNUM_GROUP  = "VNUM";
1806         static final String PRE_GROUP   = "PRE";
1807         static final String PLUS_GROUP  = "PLUS";
1808         static final String BUILD_GROUP = "BUILD";
1809         static final String OPT_GROUP   = "OPT";
1810     }
1811 }