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      * The JVM is also free to provide non-verbatim answers, for example, adding
1079      * the random offset in order to hide the real object addresses. Because of this,
1080      * this method is useful to compare the relative Object positions, or inspecting
1081      * the object alignments up to some high threshold, but not for accessing the objects
1082      * via the naked native address.
1083      * <p>
1084      * JVM may answer the "don't know" value if it does not know the address of
1085      * the specified object, or refuses to provide this information.
1086      *
1087      * @param obj object to get the address of
1088      * @return current object address, or {@code -1} if address is unknown
1089      * @since 16
1090      */
1091     @DontInline // Semantics: make sure the object is not scalar replaced.
1092     public static long addressOf(Object obj) {
1093         Objects.requireNonNull(obj);
1094         return addressOf0(obj);
1095     }
1096 
1097     @HotSpotIntrinsicCandidate
1098     private static native long addressOf0(Object obj);
1099 
1100     /**
1101      * Returns the implementation-specific estimate of the offset of the field
1102      * within the holding container.
1103      * <p>
1104      * For the instance fields, the offset is from the beginning of the holder
1105      * object. For the static fields, the offset is from the beginning of the
1106      * unspecified holder area. As such, these offsets are useful for comparing
1107      * the offsets of two fields, not for any kind of absolute addressing.
1108      * <p>
1109      * The estimate may change during a single invocation of the JVM, for example
1110      * during class redefinition.
1111      * <p>
1112      * JVM may answer the "don't know" value if it does not know the address of
1113      * the specified object, or refuses to provide this information.
1114      *
1115      * @param field field to poll
1116      * @return the field offset in bytes, or {@code -1} if field offset is unknown
1117      * @throws NullPointerException if {@code field} is {@code null}
1118      * @since 16
1119      */
1120     public static long fieldOffsetOf(Field field) {
1121         Objects.requireNonNull(field);
1122         return fieldOffsetOf0(field);
1123     }
1124 
1125     // Reflection-like call, is not supposed to be fast?
1126     private static native long fieldOffsetOf0(Field field);
1127 
1128     /**
1129      * Returns the implementation-specific estimate of the field slot size for
1130      * the specified object field.
1131      * <p>
1132      * The estimate may change during a single invocation of the JVM.
1133      * <p>
1134      * JVM may answer the "don't know" value if it does not know the address of
1135      * the specified object, or refuses to provide this information.
1136      *
1137      * TODO: Split by staticness?
1138      *
1139      * @param field field to poll
1140      * @return the field size in bytes, or {@code -1} if field size is unknown
1141      * @throws NullPointerException if {@code field} is {@code null}
1142      * @since 16
1143      */
1144     public static long fieldSizeOf(Field field) {
1145         Objects.requireNonNull(field);
1146         return fieldSizeOf0(field);
1147     }
1148 
1149     // Reflection-like call, is not supposed to be fast?
1150     private static native long fieldSizeOf0(Field field);
1151 
1152     /**
1153      * Returns the version of the Java Runtime Environment as a {@link Version}.
1154      *
1155      * @return  the {@link Version} of the Java Runtime Environment
1156      *
1157      * @since  9
1158      */
1159     public static Version version() {
1160         if (version == null) {
1161             version = new Version(VersionProps.versionNumbers(),
1162                     VersionProps.pre(), VersionProps.build(),
1163                     VersionProps.optional());
1164         }
1165         return version;
1166     }
1167 
1168     /**
1169      * A representation of a version string for an implementation of the
1170      * Java&nbsp;SE Platform.  A version string consists of a version number
1171      * optionally followed by pre-release and build information.
1172      *
1173      * <h2><a id="verNum">Version numbers</a></h2>
1174      *
1175      * <p> A <em>version number</em>, {@code $VNUM}, is a non-empty sequence of
1176      * elements separated by period characters (U+002E).  An element is either
1177      * zero, or an unsigned integer numeral without leading zeros.  The final
1178      * element in a version number must not be zero.  When an element is
1179      * incremented, all subsequent elements are removed.  The format is: </p>
1180      *
1181      * <blockquote><pre>
1182      * [1-9][0-9]*((\.0)*\.[1-9][0-9]*)*
1183      * </pre></blockquote>
1184      *
1185      * <p> The sequence may be of arbitrary length but the first four elements
1186      * are assigned specific meanings, as follows:</p>
1187      *
1188      * <blockquote><pre>
1189      * $FEATURE.$INTERIM.$UPDATE.$PATCH
1190      * </pre></blockquote>
1191      *
1192      * <ul>
1193      *
1194      * <li><p> <a id="FEATURE">{@code $FEATURE}</a> — The
1195      * feature-release counter, incremented for every feature release
1196      * regardless of release content.  Features may be added in a feature
1197      * release; they may also be removed, if advance notice was given at least
1198      * one feature release ahead of time.  Incompatible changes may be made
1199      * when justified. </p></li>
1200      *
1201      * <li><p> <a id="INTERIM">{@code $INTERIM}</a> — The
1202      * interim-release counter, incremented for non-feature releases that
1203      * contain compatible bug fixes and enhancements but no incompatible
1204      * changes, no feature removals, and no changes to standard APIs.
1205      * </p></li>
1206      *
1207      * <li><p> <a id="UPDATE">{@code $UPDATE}</a> — The update-release
1208      * counter, incremented for compatible update releases that fix security
1209      * issues, regressions, and bugs in newer features. </p></li>
1210      *
1211      * <li><p> <a id="PATCH">{@code $PATCH}</a> — The emergency
1212      * patch-release counter, incremented only when it's necessary to produce
1213      * an emergency release to fix a critical issue. </p></li>
1214      *
1215      * </ul>
1216      *
1217      * <p> The fifth and later elements of a version number are free for use by
1218      * platform implementors, to identify implementor-specific patch
1219      * releases. </p>
1220      *
1221      * <p> A version number never has trailing zero elements.  If an element
1222      * and all those that follow it logically have the value zero then all of
1223      * them are omitted. </p>
1224      *
1225      * <p> The sequence of numerals in a version number is compared to another
1226      * such sequence in numerical, pointwise fashion; <em>e.g.</em>, {@code
1227      * 10.0.4} is less than {@code 10.1.2}.  If one sequence is shorter than
1228      * another then the missing elements of the shorter sequence are considered
1229      * to be less than the corresponding elements of the longer sequence;
1230      * <em>e.g.</em>, {@code 10.0.2} is less than {@code 10.0.2.1}. </p>
1231      *
1232      * <h2><a id="verStr">Version strings</a></h2>
1233      *
1234      * <p> A <em>version string</em>, {@code $VSTR}, is a version number {@code
1235      * $VNUM}, as described above, optionally followed by pre-release and build
1236      * information, in one of the following formats: </p>
1237      *
1238      * <blockquote><pre>
1239      *     $VNUM(-$PRE)?\+$BUILD(-$OPT)?
1240      *     $VNUM-$PRE(-$OPT)?
1241      *     $VNUM(\+-$OPT)?
1242      * </pre></blockquote>
1243      *
1244      * <p> where: </p>
1245      *
1246      * <ul>
1247      *
1248      * <li><p> <a id="pre">{@code $PRE}</a>, matching {@code ([a-zA-Z0-9]+)}
1249      * — A pre-release identifier.  Typically {@code ea}, for a
1250      * potentially unstable early-access release under active development, or
1251      * {@code internal}, for an internal developer build. </p></li>
1252      *
1253      * <li><p> <a id="build">{@code $BUILD}</a>, matching {@code
1254      * (0|[1-9][0-9]*)} — The build number, incremented for each promoted
1255      * build.  {@code $BUILD} is reset to {@code 1} when any portion of {@code
1256      * $VNUM} is incremented. </p></li>
1257      *
1258      * <li><p> <a id="opt">{@code $OPT}</a>, matching {@code ([-a-zA-Z0-9.]+)}
1259      * — Additional build information, if desired.  In the case of an
1260      * {@code internal} build this will often contain the date and time of the
1261      * build. </p></li>
1262      *
1263      * </ul>
1264      *
1265      * <p> A version string {@code 10-ea} matches {@code $VNUM = "10"} and
1266      * {@code $PRE = "ea"}.  The version string {@code 10+-ea} matches
1267      * {@code $VNUM = "10"} and {@code $OPT = "ea"}. </p>
1268      *
1269      * <p> When comparing two version strings, the value of {@code $OPT}, if
1270      * present, may or may not be significant depending on the chosen
1271      * comparison method.  The comparison methods {@link #compareTo(Version)
1272      * compareTo()} and {@link #compareToIgnoreOptional(Version)
1273      * compareToIgnoreOptional()} should be used consistently with the
1274      * corresponding methods {@link #equals(Object) equals()} and {@link
1275      * #equalsIgnoreOptional(Object) equalsIgnoreOptional()}.  </p>
1276      *
1277      * <p> A <em>short version string</em>, {@code $SVSTR}, often useful in
1278      * less formal contexts, is a version number optionally followed by a
1279      * pre-release identifier:</p>
1280      *
1281      * <blockquote><pre>
1282      *     $VNUM(-$PRE)?
1283      * </pre></blockquote>
1284      *
1285      * <p>This is a <a href="./doc-files/ValueBased.html">value-based</a>
1286      * class; use of identity-sensitive operations (including reference equality
1287      * ({@code ==}), identity hash code, or synchronization) on instances of
1288      * {@code Version} may have unpredictable results and should be avoided.
1289      * </p>
1290      *
1291      * @since  9
1292      */
1293     public static final class Version
1294         implements Comparable<Version>
1295     {
1296         private final List<Integer>     version;
1297         private final Optional<String>  pre;
1298         private final Optional<Integer> build;
1299         private final Optional<String>  optional;
1300 
1301         /*
1302          * List of version number components passed to this constructor MUST
1303          * be at least unmodifiable (ideally immutable). In the case of an
1304          * unmodifiable list, the caller MUST hand the list over to this
1305          * constructor and never change the underlying list.
1306          */
1307         private Version(List<Integer> unmodifiableListOfVersions,
1308                         Optional<String> pre,
1309                         Optional<Integer> build,
1310                         Optional<String> optional)
1311         {
1312             this.version = unmodifiableListOfVersions;
1313             this.pre = pre;
1314             this.build = build;
1315             this.optional = optional;
1316         }
1317 
1318         /**
1319          * Parses the given string as a valid
1320          * <a href="#verStr">version string</a> containing a
1321          * <a href="#verNum">version number</a> followed by pre-release and
1322          * build information.
1323          *
1324          * @param  s
1325          *         A string to interpret as a version
1326          *
1327          * @throws  IllegalArgumentException
1328          *          If the given string cannot be interpreted as a valid
1329          *          version
1330          *
1331          * @throws  NullPointerException
1332          *          If the given string is {@code null}
1333          *
1334          * @throws  NumberFormatException
1335          *          If an element of the version number or the build number
1336          *          cannot be represented as an {@link Integer}
1337          *
1338          * @return  The Version of the given string
1339          */
1340         public static Version parse(String s) {
1341             if (s == null)
1342                 throw new NullPointerException();
1343 
1344             // Shortcut to avoid initializing VersionPattern when creating
1345             // feature-version constants during startup
1346             if (isSimpleNumber(s)) {
1347                 return new Version(List.of(Integer.parseInt(s)),
1348                         Optional.empty(), Optional.empty(), Optional.empty());
1349             }
1350             Matcher m = VersionPattern.VSTR_PATTERN.matcher(s);
1351             if (!m.matches())
1352                 throw new IllegalArgumentException("Invalid version string: '"
1353                                                    + s + "'");
1354 
1355             // $VNUM is a dot-separated list of integers of arbitrary length
1356             String[] split = m.group(VersionPattern.VNUM_GROUP).split("\\.");
1357             Integer[] version = new Integer[split.length];
1358             for (int i = 0; i < split.length; i++) {
1359                 version[i] = Integer.parseInt(split[i]);
1360             }
1361 
1362             Optional<String> pre = Optional.ofNullable(
1363                     m.group(VersionPattern.PRE_GROUP));
1364 
1365             String b = m.group(VersionPattern.BUILD_GROUP);
1366             // $BUILD is an integer
1367             Optional<Integer> build = (b == null)
1368                 ? Optional.empty()
1369                 : Optional.of(Integer.parseInt(b));
1370 
1371             Optional<String> optional = Optional.ofNullable(
1372                     m.group(VersionPattern.OPT_GROUP));
1373 
1374             // empty '+'
1375             if (!build.isPresent()) {
1376                 if (m.group(VersionPattern.PLUS_GROUP) != null) {
1377                     if (optional.isPresent()) {
1378                         if (pre.isPresent())
1379                             throw new IllegalArgumentException("'+' found with"
1380                                 + " pre-release and optional components:'" + s
1381                                 + "'");
1382                     } else {
1383                         throw new IllegalArgumentException("'+' found with neither"
1384                             + " build or optional components: '" + s + "'");
1385                     }
1386                 } else {
1387                     if (optional.isPresent() && !pre.isPresent()) {
1388                         throw new IllegalArgumentException("optional component"
1389                             + " must be preceded by a pre-release component"
1390                             + " or '+': '" + s + "'");
1391                     }
1392                 }
1393             }
1394             return new Version(List.of(version), pre, build, optional);
1395         }
1396 
1397         private static boolean isSimpleNumber(String s) {
1398             for (int i = 0; i < s.length(); i++) {
1399                 char c = s.charAt(i);
1400                 char lowerBound = (i > 0) ? '0' : '1';
1401                 if (c < lowerBound || c > '9') {
1402                     return false;
1403                 }
1404             }
1405             return true;
1406         }
1407 
1408         /**
1409          * Returns the value of the <a href="#FEATURE">feature</a> element of
1410          * the version number.
1411          *
1412          * @return The value of the feature element
1413          *
1414          * @since 10
1415          */
1416         public int feature() {
1417             return version.get(0);
1418         }
1419 
1420         /**
1421          * Returns the value of the <a href="#INTERIM">interim</a> element of
1422          * the version number, or zero if it is absent.
1423          *
1424          * @return The value of the interim element, or zero
1425          *
1426          * @since 10
1427          */
1428         public int interim() {
1429             return (version.size() > 1 ? version.get(1) : 0);
1430         }
1431 
1432         /**
1433          * Returns the value of the <a href="#UPDATE">update</a> element of the
1434          * version number, or zero if it is absent.
1435          *
1436          * @return The value of the update element, or zero
1437          *
1438          * @since 10
1439          */
1440         public int update() {
1441             return (version.size() > 2 ? version.get(2) : 0);
1442         }
1443 
1444         /**
1445          * Returns the value of the <a href="#PATCH">patch</a> element of the
1446          * version number, or zero if it is absent.
1447          *
1448          * @return The value of the patch element, or zero
1449          *
1450          * @since 10
1451          */
1452         public int patch() {
1453             return (version.size() > 3 ? version.get(3) : 0);
1454         }
1455 
1456         /**
1457          * Returns the value of the major element of the version number.
1458          *
1459          * @deprecated As of Java&nbsp;SE 10, the first element of a version
1460          * number is not the major-release number but the feature-release
1461          * counter, incremented for every time-based release.  Use the {@link
1462          * #feature()} method in preference to this method.  For compatibility,
1463          * this method returns the value of the <a href="#FEATURE">feature</a>
1464          * element.
1465          *
1466          * @return The value of the feature element
1467          */
1468         @Deprecated(since = "10")
1469         public int major() {
1470             return feature();
1471         }
1472 
1473         /**
1474          * Returns the value of the minor element of the version number, or
1475          * zero if it is absent.
1476          *
1477          * @deprecated As of Java&nbsp;SE 10, the second element of a version
1478          * number is not the minor-release number but the interim-release
1479          * counter, incremented for every interim release.  Use the {@link
1480          * #interim()} method in preference to this method.  For compatibility,
1481          * this method returns the value of the <a href="#INTERIM">interim</a>
1482          * element, or zero if it is absent.
1483          *
1484          * @return The value of the interim element, or zero
1485          */
1486         @Deprecated(since = "10")
1487         public int minor() {
1488             return interim();
1489         }
1490 
1491         /**
1492          * Returns the value of the security element of the version number, or
1493          * zero if it is absent.
1494          *
1495          * @deprecated As of Java&nbsp;SE 10, the third element of a version
1496          * number is not the security level but the update-release counter,
1497          * incremented for every update release.  Use the {@link #update()}
1498          * method in preference to this method.  For compatibility, this method
1499          * returns the value of the <a href="#UPDATE">update</a> element, or
1500          * zero if it is absent.
1501          *
1502          * @return  The value of the update element, or zero
1503          */
1504         @Deprecated(since = "10")
1505         public int security() {
1506             return update();
1507         }
1508 
1509         /**
1510          * Returns an unmodifiable {@link java.util.List List} of the integers
1511          * represented in the <a href="#verNum">version number</a>.
1512          * The {@code List} always contains at least one element corresponding to
1513          * the <a href="#FEATURE">feature version number</a>.
1514          *
1515          * @return  An unmodifiable list of the integers
1516          *          represented in the version number
1517          */
1518         public List<Integer> version() {
1519             return version;
1520         }
1521 
1522         /**
1523          * Returns the optional <a href="#pre">pre-release</a> information.
1524          *
1525          * @return  The optional pre-release information as a String
1526          */
1527         public Optional<String> pre() {
1528             return pre;
1529         }
1530 
1531         /**
1532          * Returns the <a href="#build">build number</a>.
1533          *
1534          * @return  The optional build number.
1535          */
1536         public Optional<Integer> build() {
1537             return build;
1538         }
1539 
1540         /**
1541          * Returns <a href="#opt">optional</a> additional identifying build
1542          * information.
1543          *
1544          * @return  Additional build information as a String
1545          */
1546         public Optional<String> optional() {
1547             return optional;
1548         }
1549 
1550         /**
1551          * Compares this version to another.
1552          *
1553          * <p> Each of the components in the <a href="#verStr">version</a> is
1554          * compared in the following order of precedence: version numbers,
1555          * pre-release identifiers, build numbers, optional build information.
1556          * </p>
1557          *
1558          * <p> Comparison begins by examining the sequence of version numbers.
1559          * If one sequence is shorter than another, then the missing elements
1560          * of the shorter sequence are considered to be less than the
1561          * corresponding elements of the longer sequence. </p>
1562          *
1563          * <p> A version with a pre-release identifier is always considered to
1564          * be less than a version without one.  Pre-release identifiers are
1565          * compared numerically when they consist only of digits, and
1566          * lexicographically otherwise.  Numeric identifiers are considered to
1567          * be less than non-numeric identifiers.  </p>
1568          *
1569          * <p> A version without a build number is always less than one with a
1570          * build number; otherwise build numbers are compared numerically. </p>
1571          *
1572          * <p> The optional build information is compared lexicographically.
1573          * During this comparison, a version with optional build information is
1574          * considered to be greater than a version without one. </p>
1575          *
1576          * @param  obj
1577          *         The object to be compared
1578          *
1579          * @return  A negative integer, zero, or a positive integer if this
1580          *          {@code Version} is less than, equal to, or greater than the
1581          *          given {@code Version}
1582          *
1583          * @throws  NullPointerException
1584          *          If the given object is {@code null}
1585          */
1586         @Override
1587         public int compareTo(Version obj) {
1588             return compare(obj, false);
1589         }
1590 
1591         /**
1592          * Compares this version to another disregarding optional build
1593          * information.
1594          *
1595          * <p> Two versions are compared by examining the version string as
1596          * described in {@link #compareTo(Version)} with the exception that the
1597          * optional build information is always ignored. </p>
1598          *
1599          * <p> This method provides ordering which is consistent with
1600          * {@code equalsIgnoreOptional()}. </p>
1601          *
1602          * @param  obj
1603          *         The object to be compared
1604          *
1605          * @return  A negative integer, zero, or a positive integer if this
1606          *          {@code Version} is less than, equal to, or greater than the
1607          *          given {@code Version}
1608          *
1609          * @throws  NullPointerException
1610          *          If the given object is {@code null}
1611          */
1612         public int compareToIgnoreOptional(Version obj) {
1613             return compare(obj, true);
1614         }
1615 
1616         private int compare(Version obj, boolean ignoreOpt) {
1617             if (obj == null)
1618                 throw new NullPointerException();
1619 
1620             int ret = compareVersion(obj);
1621             if (ret != 0)
1622                 return ret;
1623 
1624             ret = comparePre(obj);
1625             if (ret != 0)
1626                 return ret;
1627 
1628             ret = compareBuild(obj);
1629             if (ret != 0)
1630                 return ret;
1631 
1632             if (!ignoreOpt)
1633                 return compareOptional(obj);
1634 
1635             return 0;
1636         }
1637 
1638         private int compareVersion(Version obj) {
1639             int size = version.size();
1640             int oSize = obj.version().size();
1641             int min = Math.min(size, oSize);
1642             for (int i = 0; i < min; i++) {
1643                 int val = version.get(i);
1644                 int oVal = obj.version().get(i);
1645                 if (val != oVal)
1646                     return val - oVal;
1647             }
1648             return size - oSize;
1649         }
1650 
1651         private int comparePre(Version obj) {
1652             Optional<String> oPre = obj.pre();
1653             if (!pre.isPresent()) {
1654                 if (oPre.isPresent())
1655                     return 1;
1656             } else {
1657                 if (!oPre.isPresent())
1658                     return -1;
1659                 String val = pre.get();
1660                 String oVal = oPre.get();
1661                 if (val.matches("\\d+")) {
1662                     return (oVal.matches("\\d+")
1663                         ? (new BigInteger(val)).compareTo(new BigInteger(oVal))
1664                         : -1);
1665                 } else {
1666                     return (oVal.matches("\\d+")
1667                         ? 1
1668                         : val.compareTo(oVal));
1669                 }
1670             }
1671             return 0;
1672         }
1673 
1674         private int compareBuild(Version obj) {
1675             Optional<Integer> oBuild = obj.build();
1676             if (oBuild.isPresent()) {
1677                 return (build.isPresent()
1678                         ? build.get().compareTo(oBuild.get())
1679                         : -1);
1680             } else if (build.isPresent()) {
1681                 return 1;
1682             }
1683             return 0;
1684         }
1685 
1686         private int compareOptional(Version obj) {
1687             Optional<String> oOpt = obj.optional();
1688             if (!optional.isPresent()) {
1689                 if (oOpt.isPresent())
1690                     return -1;
1691             } else {
1692                 if (!oOpt.isPresent())
1693                     return 1;
1694                 return optional.get().compareTo(oOpt.get());
1695             }
1696             return 0;
1697         }
1698 
1699         /**
1700          * Returns a string representation of this version.
1701          *
1702          * @return  The version string
1703          */
1704         @Override
1705         public String toString() {
1706             StringBuilder sb
1707                 = new StringBuilder(version.stream()
1708                     .map(Object::toString)
1709                     .collect(Collectors.joining(".")));
1710 
1711             pre.ifPresent(v -> sb.append("-").append(v));
1712 
1713             if (build.isPresent()) {
1714                 sb.append("+").append(build.get());
1715                 if (optional.isPresent())
1716                     sb.append("-").append(optional.get());
1717             } else {
1718                 if (optional.isPresent()) {
1719                     sb.append(pre.isPresent() ? "-" : "+-");
1720                     sb.append(optional.get());
1721                 }
1722             }
1723 
1724             return sb.toString();
1725         }
1726 
1727         /**
1728          * Determines whether this {@code Version} is equal to another object.
1729          *
1730          * <p> Two {@code Version}s are equal if and only if they represent the
1731          * same version string.
1732          *
1733          * @param  obj
1734          *         The object to which this {@code Version} is to be compared
1735          *
1736          * @return  {@code true} if, and only if, the given object is a {@code
1737          *          Version} that is identical to this {@code Version}
1738          *
1739          */
1740         @Override
1741         public boolean equals(Object obj) {
1742             boolean ret = equalsIgnoreOptional(obj);
1743             if (!ret)
1744                 return false;
1745 
1746             Version that = (Version)obj;
1747             return (this.optional().equals(that.optional()));
1748         }
1749 
1750         /**
1751          * Determines whether this {@code Version} is equal to another
1752          * disregarding optional build information.
1753          *
1754          * <p> Two {@code Version}s are equal if and only if they represent the
1755          * same version string disregarding the optional build information.
1756          *
1757          * @param  obj
1758          *         The object to which this {@code Version} is to be compared
1759          *
1760          * @return  {@code true} if, and only if, the given object is a {@code
1761          *          Version} that is identical to this {@code Version}
1762          *          ignoring the optional build information
1763          *
1764          */
1765         public boolean equalsIgnoreOptional(Object obj) {
1766             if (this == obj)
1767                 return true;
1768             if (!(obj instanceof Version))
1769                 return false;
1770 
1771             Version that = (Version)obj;
1772             return (this.version().equals(that.version())
1773                 && this.pre().equals(that.pre())
1774                 && this.build().equals(that.build()));
1775         }
1776 
1777         /**
1778          * Returns the hash code of this version.
1779          *
1780          * @return  The hashcode of this version
1781          */
1782         @Override
1783         public int hashCode() {
1784             int h = 1;
1785             int p = 17;
1786 
1787             h = p * h + version.hashCode();
1788             h = p * h + pre.hashCode();
1789             h = p * h + build.hashCode();
1790             h = p * h + optional.hashCode();
1791 
1792             return h;
1793         }
1794     }
1795 
1796     private static class VersionPattern {
1797         // $VNUM(-$PRE)?(\+($BUILD)?(\-$OPT)?)?
1798         // RE limits the format of version strings
1799         // ([1-9][0-9]*(?:(?:\.0)*\.[1-9][0-9]*)*)(?:-([a-zA-Z0-9]+))?(?:(\+)(0|[1-9][0-9]*)?)?(?:-([-a-zA-Z0-9.]+))?
1800 
1801         private static final String VNUM
1802             = "(?<VNUM>[1-9][0-9]*(?:(?:\\.0)*\\.[1-9][0-9]*)*)";
1803         private static final String PRE      = "(?:-(?<PRE>[a-zA-Z0-9]+))?";
1804         private static final String BUILD
1805             = "(?:(?<PLUS>\\+)(?<BUILD>0|[1-9][0-9]*)?)?";
1806         private static final String OPT      = "(?:-(?<OPT>[-a-zA-Z0-9.]+))?";
1807         private static final String VSTR_FORMAT = VNUM + PRE + BUILD + OPT;
1808 
1809         static final Pattern VSTR_PATTERN = Pattern.compile(VSTR_FORMAT);
1810 
1811         static final String VNUM_GROUP  = "VNUM";
1812         static final String PRE_GROUP   = "PRE";
1813         static final String PLUS_GROUP  = "PLUS";
1814         static final String BUILD_GROUP = "BUILD";
1815         static final String OPT_GROUP   = "OPT";
1816     }
1817 }