1 /*
   2  * Copyright (c) 1994, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import java.security.AccessController;
  29 import java.security.AccessControlContext;
  30 import java.security.Permission;
  31 import java.security.PrivilegedAction;
  32 import java.security.ProtectionDomain;
  33 import java.time.Duration;
  34 import java.util.Map;
  35 import java.util.HashMap;
  36 import java.util.Objects;
  37 import java.util.concurrent.ThreadFactory;
  38 import java.util.concurrent.locks.LockSupport;
  39 import java.util.function.Predicate;
  40 import java.util.stream.Stream;
  41 import jdk.internal.event.ThreadSleepEvent;
  42 import jdk.internal.javac.PreviewFeature;
  43 import jdk.internal.misc.PreviewFeatures;
  44 import jdk.internal.misc.StructureViolationExceptions;
  45 import jdk.internal.misc.TerminatingThreadLocal;
  46 import jdk.internal.misc.Unsafe;
  47 import jdk.internal.misc.VM;
  48 import jdk.internal.reflect.CallerSensitive;
  49 import jdk.internal.reflect.Reflection;
  50 import jdk.internal.vm.Continuation;
  51 import jdk.internal.vm.ExtentLocalContainer;
  52 import jdk.internal.vm.StackableScope;
  53 import jdk.internal.vm.ThreadContainer;
  54 import jdk.internal.vm.annotation.IntrinsicCandidate;
  55 import sun.nio.ch.Interruptible;
  56 import sun.security.util.SecurityConstants;
  57 import static java.util.concurrent.TimeUnit.MILLISECONDS;
  58 import static java.util.concurrent.TimeUnit.NANOSECONDS;
  59 
  60 /**
  61  * A <i>thread</i> is a thread of execution in a program. The Java
  62  * virtual machine allows an application to have multiple threads of
  63  * execution running concurrently.
  64  *
  65  * <p> {@code Thread} defines constructors and a {@link Builder} to create threads.
  66  * {@linkplain #start() Starting} a thread schedules it to execute its {@link #run() run}
  67  * method. The newly started thread executes concurrently with the thread that caused
  68  * it to start.
  69  *
  70  * <p> A thread <i>terminates</i> if either its {@code run} method completes normally,
  71  * or if its {@code run} method completes abruptly and the appropriate {@linkplain
  72  * Thread.UncaughtExceptionHandler uncaught exception handler} completes normally or
  73  * abruptly. With no code left to run, the thread has completed execution. The
  74  * {@link #join() join} method can be used to wait for a thread to terminate.
  75  *
  76  * <p> Threads have a unique {@linkplain #threadId() identifier} and a {@linkplain
  77  * #getName() name}. The identifier is generated when a {@code Thread} is created
  78  * and cannot be changed. The thread name can be specified when creating a thread
  79  * or can be {@linkplain #setName(String) changed} at a later time.
  80  *
  81  * <p> Threads support {@link ThreadLocal} variables. These are variables that are
  82  * local to a thread, meaning a thread can have a copy of a variable that is set to
  83  * a value that is independent of the value set by other threads. Thread also supports
  84  * {@link InheritableThreadLocal} variables that are thread local variables that are
  85  * inherited at Thread creation time from the parent Thread. Thread supports a special
  86  * inheritable thread local for the thread {@linkplain #getContextClassLoader()
  87  * context-class-loader}.
  88  *
  89  * <h2><a id="platform-threads">Platform threads</a></h2>
  90  * <p> {@code Thread} supports the creation of <i>platform threads</i> that are
  91  * typically mapped 1:1 to kernel threads scheduled by the operating system.
  92  * Platform threads will usually have a large stack and other resources that are
  93  * maintained by the operating system. Platforms threads are suitable for executing
  94  * all types of tasks but may be a limited resource.
  95  *
  96  * <p> Platform threads get an automatically generated thread name by default.
  97  *
  98  * <p> Platform threads are designated <i>daemon</i> or <i>non-daemon</i> threads.
  99  * When the Java virtual machine starts up, there is usually one non-daemon
 100  * thread (the thread that typically calls the application's {@code main} method).
 101  * The <a href="Runtime.html#shutdown">shutdown sequence</a> begins when all started
 102  * non-daemon threads have terminated. Unstarted non-daemon threads do not prevent
 103  * the shutdown sequence from beginning.
 104  *
 105  * <p> In addition to the daemon status, platform threads have a {@linkplain
 106  * #getPriority() thread priority} and are members of a {@linkplain ThreadGroup
 107  * thread group}.
 108  *
 109  * <h2><a id="virtual-threads">Virtual threads</a></h2>
 110  * <p> {@code Thread} also supports the creation of <i>virtual threads</i>.
 111  * Virtual threads are typically <i>user-mode threads</i> scheduled by the Java
 112  * runtime rather than the operating system. Virtual threads will typically require
 113  * few resources and a single Java virtual machine may support millions of virtual
 114  * threads. Virtual threads are suitable for executing tasks that spend most of
 115  * the time blocked, often waiting for I/O operations to complete. Virtual threads
 116  * are not intended for long running CPU intensive operations.
 117  *
 118  * <p> Virtual threads typically employ a small set of platform threads used as
 119  * <em>carrier threads</em>. Locking and I/O operations are examples of operations
 120  * where a carrier thread may be re-scheduled from one virtual thread to another.
 121  * Code executing in a virtual thread is not aware of the underlying carrier thread.
 122  * The {@linkplain Thread#currentThread()} method, used to obtain a reference
 123  * to the <i>current thread</i>, will always return the {@code Thread} object
 124  * for the virtual thread.
 125  *
 126  * <p> Virtual threads do not have a thread name by default. The {@link #getName()
 127  * getName} method returns the empty string if a thread name is not set.
 128  *
 129  * <p> Virtual threads are daemon threads and so do not prevent the
 130  * <a href="Runtime.html#shutdown">shutdown sequence</a> from beginning.
 131  * Virtual threads have a fixed {@linkplain #getPriority() thread priority}
 132  * that cannot be changed.
 133  *
 134  * <h2>Creating and starting threads</h2>
 135  *
 136  * <p> {@code Thread} defines public constructors for creating platform threads and
 137  * the {@link #start() start} method to schedule threads to execute. {@code Thread}
 138  * may be extended for customization and other advanced reasons although most
 139  * applications should have little need to do this.
 140  *
 141  * <p> {@code Thread} defines a {@link Builder} API for creating and starting both
 142  * platform and virtual threads. The following are examples that use the builder:
 143  * {@snippet :
 144  *   Runnable runnable = ...
 145  *
 146  *   // Start a daemon thread to run a task
 147  *   Thread thread = Thread.ofPlatform().daemon().start(runnable);
 148  *
 149  *   // Create an unstarted thread with name "duke", its start() method
 150  *   // must be invoked to schedule it to execute.
 151  *   Thread thread = Thread.ofPlatform().name("duke").unstarted(runnable);
 152  *
 153  *   // A ThreadFactory that creates daemon threads named "worker-0", "worker-1", ...
 154  *   ThreadFactory factory = Thread.ofPlatform().daemon().name("worker-", 0).factory();
 155  *
 156  *   // Start a virtual thread to run a task
 157  *   Thread thread = Thread.ofVirtual().start(runnable);
 158  *
 159  *   // A ThreadFactory that creates virtual threads
 160  *   ThreadFactory factory = Thread.ofVirtual().factory();
 161  * }
 162  *
 163  * <h2><a id="inheritance">Inheritance when creating threads</a></h2>
 164  * A {@code Thread} inherits its initial values of {@linkplain InheritableThreadLocal
 165  * inheritable-thread-local} variables (including the context class loader) from
 166  * the parent thread values at the time that the child {@code Thread} is created.
 167  * The 5-param {@linkplain Thread#Thread(ThreadGroup, Runnable, String, long, boolean)
 168  * constructor} can be used to create a thread that does not inherit its initial
 169  * values from the constructing thread. When using a {@code Thread.Builder}, the
 170  * {@link Builder#inheritInheritableThreadLocals(boolean) inheritInheritableThreadLocals}
 171  * method can be used to select if the initial values are inherited.
 172  *
 173  * <p> Platform threads inherit the daemon status, thread priority, and when not
 174  * provided (or not selected by a security manager), the thread group.
 175  *
 176  * <p> Creating a platform thread {@linkplain AccessController#getContext() captures} the
 177  * {@linkplain AccessControlContext caller context} to limit the {@linkplain Permission
 178  * permissions} of the new thread when it executes code that performs a {@linkplain
 179  * AccessController#doPrivileged(PrivilegedAction) privileged action}. The captured
 180  * caller context is the new thread's "Inherited {@link AccessControlContext}". Creating
 181  * a virtual thread does not capture the caller context; virtual threads have no
 182  * permissions when executing code that performs a privileged action.
 183  *
 184  * <p> Unless otherwise specified, passing a {@code null} argument to a constructor
 185  * or method in this class will cause a {@link NullPointerException} to be thrown.
 186  *
 187  * @implNote
 188  * In the JDK Reference Implementation, the virtual thread scheduler may be configured
 189  * with the following system properties:
 190  * <table class="striped">
 191  * <caption style="display:none:">System properties</caption>
 192  *   <thead>
 193  *   <tr>
 194  *     <th scope="col">System property</th>
 195  *     <th scope="col">Description</th>
 196  *   </tr>
 197  *   </thead>
 198  *   <tbody>
 199  *   <tr>
 200  *     <th scope="row">
 201  *       {@systemProperty jdk.virtualThreadScheduler.parallelism}
 202  *     </th>
 203  *     <td> The number of platform threads available for scheduling virtual
 204  *       threads. It defaults to the number of available processors. </td>
 205  *   </tr>
 206  *   <tr>
 207  *     <th scope="row">
 208  *       {@systemProperty jdk.virtualThreadScheduler.maxPoolSize}
 209  *     </th>
 210  *     <td> The maximum number of platform threads available to the scheduler.
 211  *       It defaults to 256. </td>
 212  *   </tr>
 213  *   </tbody>
 214  * </table>
 215  *
 216  * @since   1.0
 217  */
 218 public class Thread implements Runnable {
 219     /* Make sure registerNatives is the first thing <clinit> does. */
 220     private static native void registerNatives();
 221     static {
 222         registerNatives();
 223     }
 224 
 225     /* Reserved for exclusive use by the JVM, maybe move to FieldHolder */
 226     private long eetop;
 227 
 228     // thread id
 229     private final long tid;
 230 
 231     // thread name
 232     private volatile String name;
 233 
 234     // interrupt status (read/written by VM)
 235     volatile boolean interrupted;
 236 
 237     // context ClassLoader
 238     private volatile ClassLoader contextClassLoader;
 239 
 240     // inherited AccessControlContext, this could be moved to FieldHolder
 241     @SuppressWarnings("removal")
 242     private AccessControlContext inheritedAccessControlContext;
 243 
 244     // Additional fields for platform threads.
 245     // All fields, except task, are accessed directly by the VM.
 246     private static class FieldHolder {
 247         final ThreadGroup group;
 248         final Runnable task;
 249         final long stackSize;
 250         volatile int priority;
 251         volatile boolean daemon;
 252         volatile int threadStatus;
 253 
 254         FieldHolder(ThreadGroup group,
 255                     Runnable task,
 256                     long stackSize,
 257                     int priority,
 258                     boolean daemon) {
 259             this.group = group;
 260             this.task = task;
 261             this.stackSize = stackSize;
 262             this.priority = priority;
 263             if (daemon)
 264                 this.daemon = true;
 265         }
 266     }
 267     private final FieldHolder holder;
 268 
 269     /*
 270      * ThreadLocal values pertaining to this thread. This map is maintained
 271      * by the ThreadLocal class. */
 272     ThreadLocal.ThreadLocalMap threadLocals;
 273 
 274     /*
 275      * InheritableThreadLocal values pertaining to this thread. This map is
 276      * maintained by the InheritableThreadLocal class.
 277      */
 278     ThreadLocal.ThreadLocalMap inheritableThreadLocals;
 279 
 280     /*
 281      * Extent locals binding are maintained by the ExtentLocal class.
 282      */
 283     private Object extentLocalBindings;
 284 
 285     static Object extentLocalBindings() {
 286         return currentThread().extentLocalBindings;
 287     }
 288 
 289     static void setExtentLocalBindings(Object bindings) {
 290         currentThread().extentLocalBindings = bindings;
 291     }
 292 
 293     /**
 294      * Inherit the extent-local bindings from the given container.
 295      * Invoked when starting a thread.
 296      */
 297     void inheritExtentLocalBindings(ThreadContainer container) {
 298         ExtentLocalContainer.BindingsSnapshot snapshot;
 299         if (container.owner() != null
 300                 && (snapshot = container.extentLocalBindings()) != null) {
 301 
 302             // bindings established for running/calling an operation
 303             Object bindings = snapshot.extentLocalBindings();
 304             if (currentThread().extentLocalBindings != bindings) {
 305                 StructureViolationExceptions.throwException("Extent local bindings have changed");
 306             }
 307 
 308             this.extentLocalBindings = bindings;
 309         }
 310     }
 311 
 312     /*
 313      * Lock object for thread interrupt.
 314      */
 315     final Object interruptLock = new Object();
 316 
 317     /**
 318      * The argument supplied to the current call to
 319      * java.util.concurrent.locks.LockSupport.park.
 320      * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
 321      * Accessed using java.util.concurrent.locks.LockSupport.getBlocker
 322      */
 323     private volatile Object parkBlocker;
 324 
 325     /* The object in which this thread is blocked in an interruptible I/O
 326      * operation, if any.  The blocker's interrupt method should be invoked
 327      * after setting this thread's interrupt status.
 328      */
 329     volatile Interruptible nioBlocker;
 330 
 331     /* Set the blocker field; invoked via jdk.internal.access.SharedSecrets
 332      * from java.nio code
 333      */
 334     static void blockedOn(Interruptible b) {
 335         Thread me = Thread.currentThread();
 336         synchronized (me.interruptLock) {
 337             me.nioBlocker = b;
 338         }
 339     }
 340 
 341     /**
 342      * The minimum priority that a thread can have.
 343      */
 344     public static final int MIN_PRIORITY = 1;
 345 
 346     /**
 347      * The default priority that is assigned to a thread.
 348      */
 349     public static final int NORM_PRIORITY = 5;
 350 
 351     /**
 352      * The maximum priority that a thread can have.
 353      */
 354     public static final int MAX_PRIORITY = 10;
 355 
 356     /*
 357      * Current inner-most continuation.
 358      */
 359     private Continuation cont;
 360 
 361     /**
 362      * Returns the current continuation.
 363      */
 364     Continuation getContinuation() {
 365         return cont;
 366     }
 367 
 368     /**
 369      * Sets the current continuation.
 370      */
 371     void setContinuation(Continuation cont) {
 372         this.cont = cont;
 373     }
 374 
 375     /**
 376      * Returns the Thread object for the current platform thread. If the
 377      * current thread is a virtual thread then this method returns the carrier.
 378      */
 379     @IntrinsicCandidate
 380     static native Thread currentCarrierThread();
 381 
 382     /**
 383      * Returns the Thread object for the current thread.
 384      * @return  the current thread
 385      */
 386     @IntrinsicCandidate
 387     public static native Thread currentThread();
 388 
 389     /**
 390      * Sets the Thread object to be returned by Thread.currentThread().
 391      */
 392     @IntrinsicCandidate
 393     native void setCurrentThread(Thread thread);
 394 
 395     // ExtentLocal support:
 396 
 397     @IntrinsicCandidate
 398     static native Object[] extentLocalCache();
 399 
 400     @IntrinsicCandidate
 401     static native void setExtentLocalCache(Object[] cache);
 402 
 403     /**
 404      * A hint to the scheduler that the current thread is willing to yield
 405      * its current use of a processor. The scheduler is free to ignore this
 406      * hint.
 407      *
 408      * <p> Yield is a heuristic attempt to improve relative progression
 409      * between threads that would otherwise over-utilise a CPU. Its use
 410      * should be combined with detailed profiling and benchmarking to
 411      * ensure that it actually has the desired effect.
 412      *
 413      * <p> It is rarely appropriate to use this method. It may be useful
 414      * for debugging or testing purposes, where it may help to reproduce
 415      * bugs due to race conditions. It may also be useful when designing
 416      * concurrency control constructs such as the ones in the
 417      * {@link java.util.concurrent.locks} package.
 418      */
 419     public static void yield() {
 420         if (currentThread() instanceof VirtualThread vthread) {
 421             vthread.tryYield();
 422         } else {
 423             yield0();
 424         }
 425     }
 426 
 427     private static native void yield0();
 428 
 429     /**
 430      * Causes the currently executing thread to sleep (temporarily cease
 431      * execution) for the specified number of milliseconds, subject to
 432      * the precision and accuracy of system timers and schedulers. The thread
 433      * does not lose ownership of any monitors.
 434      *
 435      * @param  millis
 436      *         the length of time to sleep in milliseconds
 437      *
 438      * @throws  IllegalArgumentException
 439      *          if the value of {@code millis} is negative
 440      *
 441      * @throws  InterruptedException
 442      *          if any thread has interrupted the current thread. The
 443      *          <i>interrupted status</i> of the current thread is
 444      *          cleared when this exception is thrown.
 445      */
 446     public static void sleep(long millis) throws InterruptedException {
 447         if (millis < 0) {
 448             throw new IllegalArgumentException("timeout value is negative");
 449         }
 450 
 451         if (currentThread() instanceof VirtualThread vthread) {
 452             long nanos = MILLISECONDS.toNanos(millis);
 453             vthread.sleepNanos(nanos);
 454             return;
 455         }
 456 
 457         if (ThreadSleepEvent.isTurnedOn()) {
 458             ThreadSleepEvent event = new ThreadSleepEvent();
 459             try {
 460                 event.time = MILLISECONDS.toNanos(millis);
 461                 event.begin();
 462                 sleep0(millis);
 463             } finally {
 464                 event.commit();
 465             }
 466         } else {
 467             sleep0(millis);
 468         }
 469     }
 470 
 471     private static native void sleep0(long millis) throws InterruptedException;
 472 
 473     /**
 474      * Causes the currently executing thread to sleep (temporarily cease
 475      * execution) for the specified number of milliseconds plus the specified
 476      * number of nanoseconds, subject to the precision and accuracy of system
 477      * timers and schedulers. The thread does not lose ownership of any
 478      * monitors.
 479      *
 480      * @param  millis
 481      *         the length of time to sleep in milliseconds
 482      *
 483      * @param  nanos
 484      *         {@code 0-999999} additional nanoseconds to sleep
 485      *
 486      * @throws  IllegalArgumentException
 487      *          if the value of {@code millis} is negative, or the value of
 488      *          {@code nanos} is not in the range {@code 0-999999}
 489      *
 490      * @throws  InterruptedException
 491      *          if any thread has interrupted the current thread. The
 492      *          <i>interrupted status</i> of the current thread is
 493      *          cleared when this exception is thrown.
 494      */
 495     public static void sleep(long millis, int nanos) throws InterruptedException {
 496         if (millis < 0) {
 497             throw new IllegalArgumentException("timeout value is negative");
 498         }
 499 
 500         if (nanos < 0 || nanos > 999999) {
 501             throw new IllegalArgumentException("nanosecond timeout value out of range");
 502         }
 503 
 504         if (currentThread() instanceof VirtualThread vthread) {
 505             // total sleep time, in nanoseconds
 506             long totalNanos = MILLISECONDS.toNanos(millis);
 507             totalNanos += Math.min(Long.MAX_VALUE - totalNanos, nanos);
 508             vthread.sleepNanos(totalNanos);
 509             return;
 510         }
 511 
 512         if (nanos > 0 && millis < Long.MAX_VALUE) {
 513             millis++;
 514         }
 515         sleep(millis);
 516     }
 517 
 518     /**
 519      * Causes the currently executing thread to sleep (temporarily cease
 520      * execution) for the specified duration, subject to the precision and
 521      * accuracy of system timers and schedulers. This method is a no-op if
 522      * the duration is {@linkplain Duration#isNegative() negative}.
 523      *
 524      * @param  duration
 525      *         the duration to sleep
 526      *
 527      * @throws  InterruptedException
 528      *          if the current thread is interrupted while sleeping. The
 529      *          <i>interrupted status</i> of the current thread is
 530      *          cleared when this exception is thrown.
 531      *
 532      * @since 19
 533      */
 534     public static void sleep(Duration duration) throws InterruptedException {
 535         long nanos = NANOSECONDS.convert(duration);  // MAX_VALUE if > 292 years
 536         if (nanos < 0)
 537             return;
 538 
 539         if (currentThread() instanceof VirtualThread vthread) {
 540             vthread.sleepNanos(nanos);
 541             return;
 542         }
 543 
 544         // convert to milliseconds
 545         long millis = MILLISECONDS.convert(nanos, NANOSECONDS);
 546         if (nanos > NANOSECONDS.convert(millis, MILLISECONDS)) {
 547             millis += 1L;
 548         }
 549         sleep(millis);
 550     }
 551 
 552     /**
 553      * Indicates that the caller is momentarily unable to progress, until the
 554      * occurrence of one or more actions on the part of other activities. By
 555      * invoking this method within each iteration of a spin-wait loop construct,
 556      * the calling thread indicates to the runtime that it is busy-waiting.
 557      * The runtime may take action to improve the performance of invoking
 558      * spin-wait loop constructions.
 559      *
 560      * @apiNote
 561      * As an example consider a method in a class that spins in a loop until
 562      * some flag is set outside of that method. A call to the {@code onSpinWait}
 563      * method should be placed inside the spin loop.
 564      * {@snippet :
 565      *     class EventHandler {
 566      *         volatile boolean eventNotificationNotReceived;
 567      *         void waitForEventAndHandleIt() {
 568      *             while ( eventNotificationNotReceived ) {
 569      *                 Thread.onSpinWait();
 570      *             }
 571      *             readAndProcessEvent();
 572      *         }
 573      *
 574      *         void readAndProcessEvent() {
 575      *             // Read event from some source and process it
 576      *              . . .
 577      *         }
 578      *     }
 579      * }
 580      * <p>
 581      * The code above would remain correct even if the {@code onSpinWait}
 582      * method was not called at all. However on some architectures the Java
 583      * Virtual Machine may issue the processor instructions to address such
 584      * code patterns in a more beneficial way.
 585      *
 586      * @since 9
 587      */
 588     @IntrinsicCandidate
 589     public static void onSpinWait() {}
 590 
 591     /**
 592      * Characteristic value signifying that the thread cannot set values for its
 593      * copy of {@link ThreadLocal thread-locals}.
 594      * See Thread initialization.
 595      */
 596     static final int NO_THREAD_LOCALS = 1 << 1;
 597 
 598     /**
 599      * Characteristic value signifying that initial values for {@link
 600      * InheritableThreadLocal inheritable-thread-locals} are not inherited from
 601      * the constructing thread.
 602      * See Thread initialization.
 603      */
 604     static final int NO_INHERIT_THREAD_LOCALS = 1 << 2;
 605 
 606     /**
 607      * Helper class to generate thread identifiers. The identifiers start at
 608      * 2 as this class cannot be used during early startup to generate the
 609      * identifier for the primordial thread. The counter is off-heap and
 610      * shared with the VM to allow it assign thread identifiers to non-Java
 611      * threads.
 612      * See Thread initialization.
 613      */
 614     private static class ThreadIdentifiers {
 615         private static final Unsafe U;
 616         private static final long NEXT_TID_OFFSET;
 617         static {
 618             U = Unsafe.getUnsafe();
 619             NEXT_TID_OFFSET = Thread.getNextThreadIdOffset();
 620         }
 621         static long next() {
 622             return U.getAndAddLong(null, NEXT_TID_OFFSET, 1);
 623         }
 624     }
 625 
 626     /**
 627      * Returns the context class loader to inherit from the parent thread.
 628      * See Thread initialization.
 629      */
 630     private static ClassLoader contextClassLoader(Thread parent) {
 631         @SuppressWarnings("removal")
 632         SecurityManager sm = System.getSecurityManager();
 633         if (sm == null || isCCLOverridden(parent.getClass())) {
 634             return parent.getContextClassLoader();
 635         } else {
 636             // skip call to getContextClassLoader
 637             ClassLoader cl = parent.contextClassLoader;
 638             return (isSupportedClassLoader(cl)) ? cl : ClassLoader.getSystemClassLoader();
 639         }
 640     }
 641 
 642     /**
 643      * Initializes a platform Thread.
 644      *
 645      * @param g the Thread group, can be null
 646      * @param name the name of the new Thread
 647      * @param characteristics thread characteristics
 648      * @param task the object whose run() method gets called
 649      * @param stackSize the desired stack size for the new thread, or
 650      *        zero to indicate that this parameter is to be ignored.
 651      * @param acc the AccessControlContext to inherit, or
 652      *        AccessController.getContext() if null
 653      */
 654     @SuppressWarnings("removal")
 655     Thread(ThreadGroup g, String name, int characteristics, Runnable task,
 656            long stackSize, AccessControlContext acc) {
 657 
 658         Thread parent = currentThread();
 659         boolean attached = (parent == this);   // primordial or JNI attached
 660 
 661         if (attached) {
 662             if (g == null) {
 663                 throw new InternalError("group cannot be null when attaching");
 664             }
 665             this.holder = new FieldHolder(g, task, stackSize, NORM_PRIORITY, false);
 666         } else {
 667             SecurityManager sm = System.getSecurityManager();
 668             if (g == null) {
 669                 // the security manager can choose the thread group
 670                 if (sm != null) {
 671                     g = sm.getThreadGroup();
 672                 }
 673 
 674                 // default to current thread's group
 675                 if (g == null) {
 676                     g = parent.getThreadGroup();
 677                 }
 678             }
 679 
 680             // permission checks when creating a child Thread
 681             if (sm != null) {
 682                 sm.checkAccess(g);
 683                 if (isCCLOverridden(getClass())) {
 684                     sm.checkPermission(SecurityConstants.SUBCLASS_IMPLEMENTATION_PERMISSION);
 685                 }
 686             }
 687 
 688             int priority = Math.min(parent.getPriority(), g.getMaxPriority());
 689             this.holder = new FieldHolder(g, task, stackSize, priority, parent.isDaemon());
 690         }
 691 
 692         if (attached && VM.initLevel() < 1) {
 693             this.tid = 1;  // primordial thread
 694         } else {
 695             this.tid = ThreadIdentifiers.next();
 696         }
 697         this.name = (name != null) ? name : genThreadName();
 698 
 699         if (acc != null) {
 700             this.inheritedAccessControlContext = acc;
 701         } else {
 702             this.inheritedAccessControlContext = AccessController.getContext();
 703         }
 704 
 705         // thread locals
 706         if (!attached) {
 707             if ((characteristics & NO_THREAD_LOCALS) != 0) {
 708                 this.threadLocals = ThreadLocal.ThreadLocalMap.NOT_SUPPORTED;
 709                 this.inheritableThreadLocals = ThreadLocal.ThreadLocalMap.NOT_SUPPORTED;
 710                 this.contextClassLoader = Constants.NOT_SUPPORTED_CLASSLOADER;
 711             } else if ((characteristics & NO_INHERIT_THREAD_LOCALS) == 0) {
 712                 ThreadLocal.ThreadLocalMap parentMap = parent.inheritableThreadLocals;
 713                 if (parentMap != null
 714                         && parentMap != ThreadLocal.ThreadLocalMap.NOT_SUPPORTED
 715                         && parentMap.size() > 0) {
 716                     this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parentMap);
 717                 }
 718                 ClassLoader parentLoader = contextClassLoader(parent);
 719                 if (VM.isBooted() && !isSupportedClassLoader(parentLoader)) {
 720                     // parent does not support thread locals so no CCL to inherit
 721                     this.contextClassLoader = ClassLoader.getSystemClassLoader();
 722                 } else {
 723                     this.contextClassLoader = parentLoader;
 724                 }
 725             } else if (VM.isBooted()) {
 726                 // default CCL to the system class loader when not inheriting
 727                 this.contextClassLoader = ClassLoader.getSystemClassLoader();
 728             }
 729         }
 730     }
 731 
 732     /**
 733      * Initializes a virtual Thread.
 734      *
 735      * @param name thread name, can be null
 736      * @param characteristics thread characteristics
 737      * @param bound true when bound to an OS thread
 738      */
 739     Thread(String name, int characteristics, boolean bound) {
 740         this.tid = ThreadIdentifiers.next();
 741         this.name = (name != null) ? name : "";
 742         this.inheritedAccessControlContext = Constants.NO_PERMISSIONS_ACC;
 743 
 744         // thread locals
 745         if ((characteristics & NO_THREAD_LOCALS) != 0) {
 746             this.threadLocals = ThreadLocal.ThreadLocalMap.NOT_SUPPORTED;
 747             this.inheritableThreadLocals = ThreadLocal.ThreadLocalMap.NOT_SUPPORTED;
 748             this.contextClassLoader = Constants.NOT_SUPPORTED_CLASSLOADER;
 749         } else if ((characteristics & NO_INHERIT_THREAD_LOCALS) == 0) {
 750             Thread parent = currentThread();
 751             ThreadLocal.ThreadLocalMap parentMap = parent.inheritableThreadLocals;
 752             if (parentMap != null
 753                     && parentMap != ThreadLocal.ThreadLocalMap.NOT_SUPPORTED
 754                     && parentMap.size() > 0) {
 755                 this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parentMap);
 756             }
 757             ClassLoader parentLoader = contextClassLoader(parent);
 758             if (isSupportedClassLoader(parentLoader)) {
 759                 this.contextClassLoader = parentLoader;
 760             } else {
 761                 // parent does not support thread locals so no CCL to inherit
 762                 this.contextClassLoader = ClassLoader.getSystemClassLoader();
 763             }
 764         } else {
 765             // default CCL to the system class loader when not inheriting
 766             this.contextClassLoader = ClassLoader.getSystemClassLoader();
 767         }
 768 
 769         // create a FieldHolder object, needed when bound to an OS thread
 770         if (bound) {
 771             ThreadGroup g = Constants.VTHREAD_GROUP;
 772             int pri = NORM_PRIORITY;
 773             this.holder = new FieldHolder(g, null, -1, pri, true);
 774         } else {
 775             this.holder = null;
 776         }
 777     }
 778 
 779     /**
 780      * Returns a builder for creating a platform {@code Thread} or {@code ThreadFactory}
 781      * that creates platform threads.
 782      *
 783      * <p> <a id="ofplatform-security"><b>Interaction with security manager when
 784      * creating platform threads</b></a>
 785      * <p> Creating a platform thread when there is a security manager set will
 786      * invoke the security manager's {@link SecurityManager#checkAccess(ThreadGroup)
 787      * checkAccess(ThreadGroup)} method with the thread's thread group.
 788      * If the thread group has not been set with the {@link
 789      * Builder.OfPlatform#group(ThreadGroup) OfPlatform.group} method then the
 790      * security manager's {@link SecurityManager#getThreadGroup() getThreadGroup}
 791      * method will be invoked first to select the thread group. If the security
 792      * manager {@code getThreadGroup} method returns {@code null} then the thread
 793      * group of the constructing thread is used.
 794      *
 795      * @apiNote The following are examples using the builder:
 796      * {@snippet :
 797      *   // Start a daemon thread to run a task
 798      *   Thread thread = Thread.ofPlatform().daemon().start(runnable);
 799      *
 800      *   // Create an unstarted thread with name "duke", its start() method
 801      *   // must be invoked to schedule it to execute.
 802      *   Thread thread = Thread.ofPlatform().name("duke").unstarted(runnable);
 803      *
 804      *   // A ThreadFactory that creates daemon threads named "worker-0", "worker-1", ...
 805      *   ThreadFactory factory = Thread.ofPlatform().daemon().name("worker-", 0).factory();
 806      * }
 807      *
 808      * @return A builder for creating {@code Thread} or {@code ThreadFactory} objects.
 809      * @since 19
 810      */
 811     @PreviewFeature(feature = PreviewFeature.Feature.VIRTUAL_THREADS)
 812     public static Builder.OfPlatform ofPlatform() {
 813         return new ThreadBuilders.PlatformThreadBuilder();
 814     }
 815 
 816     /**
 817      * Returns a builder for creating a virtual {@code Thread} or {@code ThreadFactory}
 818      * that creates virtual threads.
 819      *
 820      * @apiNote The following are examples using the builder:
 821      * {@snippet :
 822      *   // Start a virtual thread to run a task.
 823      *   Thread thread = Thread.ofVirtual().start(runnable);
 824      *
 825      *   // A ThreadFactory that creates virtual threads
 826      *   ThreadFactory factory = Thread.ofVirtual().factory();
 827      * }
 828      *
 829      * @return A builder for creating {@code Thread} or {@code ThreadFactory} objects.
 830      * @throws UnsupportedOperationException if preview features are not enabled
 831      * @since 19
 832      */
 833     @PreviewFeature(feature = PreviewFeature.Feature.VIRTUAL_THREADS)
 834     public static Builder.OfVirtual ofVirtual() {
 835         PreviewFeatures.ensureEnabled();
 836         return new ThreadBuilders.VirtualThreadBuilder();
 837     }
 838 
 839     /**
 840      * A builder for {@link Thread} and {@link ThreadFactory} objects.
 841      *
 842      * <p> {@code Builder} defines methods to set {@code Thread} properties such
 843      * as the thread {@link #name(String) name}. This includes properties that would
 844      * otherwise be <a href="Thread.html#inheritance">inherited</a>. Once set, a
 845      * {@code Thread} or {@code ThreadFactory} is created with the following methods:
 846      *
 847      * <ul>
 848      *     <li> The {@linkplain #unstarted(Runnable) unstarted} method creates a new
 849      *          <em>unstarted</em> {@code Thread} to run a task. The {@code Thread}'s
 850      *          {@link Thread#start() start} method must be invoked to schedule the
 851      *          thread to execute.
 852      *     <li> The {@linkplain #start(Runnable) start} method creates a new {@code
 853      *          Thread} to run a task and schedules the thread to execute.
 854      *     <li> The {@linkplain #factory() factory} method creates a {@code ThreadFactory}.
 855      * </ul>
 856      *
 857      * <p> A {@code Thread.Builder} is not thread safe. The {@code ThreadFactory}
 858      * returned by the builder's {@code factory()} method is thread safe.
 859      *
 860      * <p> Unless otherwise specified, passing a null argument to a method in
 861      * this interface causes a {@code NullPointerException} to be thrown.
 862      *
 863      * @see Thread#ofPlatform()
 864      * @see Thread#ofVirtual()
 865      * @since 19
 866      */
 867     @PreviewFeature(feature = PreviewFeature.Feature.VIRTUAL_THREADS)
 868     public sealed interface Builder
 869             permits Builder.OfPlatform,
 870                     Builder.OfVirtual,
 871                     ThreadBuilders.BaseThreadBuilder {
 872 
 873 
 874         /**
 875          * Sets the thread name.
 876          * @param name thread name
 877          * @return this builder
 878          */
 879         Builder name(String name);
 880 
 881         /**
 882          * Sets the thread name to be the concatenation of a string prefix and
 883          * the string representation of a counter value. The counter's initial
 884          * value is {@code start}. It is incremented after a {@code Thread} is
 885          * created with this builder so that the next thread is named with
 886          * the new counter value. A {@code ThreadFactory} created with this
 887          * builder is seeded with the current value of the counter. The {@code
 888          * ThreadFactory} increments its copy of the counter after {@link
 889          * ThreadFactory#newThread(Runnable) newThread} is used to create a
 890          * {@code Thread}.
 891          *
 892          * @apiNote
 893          * The following example creates a builder that is invoked twice to start
 894          * two threads named "{@code worker-0}" and "{@code worker-1}".
 895          * {@snippet :
 896          *   Thread.Builder builder = Thread.ofPlatform().name("worker-", 0);
 897          *   Thread t1 = builder.start(task1);   // name "worker-0"
 898          *   Thread t2 = builder.start(task2);   // name "worker-1"
 899          * }
 900          *
 901          * @param prefix thread name prefix
 902          * @param start the starting value of the counter
 903          * @return this builder
 904          * @throws IllegalArgumentException if start is negative
 905          */
 906         Builder name(String prefix, long start);
 907 
 908         /**
 909          * Sets whether the thread is allowed to set values for its copy of {@linkplain
 910          * ThreadLocal thread-local} variables. The default is to allow. If not allowed,
 911          * then any attempt by the thread to set a value for a thread-local with the
 912          * {@link ThreadLocal#set(Object)} method throws {@code
 913          * UnsupportedOperationException}. Any attempt to set the thread's context
 914          * class loader with {@link Thread#setContextClassLoader(ClassLoader)
 915          * setContextClassLoader} also throws. The {@link ThreadLocal#get()} method
 916          * always returns the {@linkplain ThreadLocal#initialValue() initial-value}
 917          * when thread locals are not allowed.
 918          *
 919          * @apiNote This method is intended for cases where there are a large number of
 920          * threads and where potentially unbounded memory usage due to thread locals is
 921          * a concern. Disallowing a thread to set its copy of thread-local variables
 922          * creates the potential for exceptions at run-time so great care is required
 923          * when the thread is used to invoke arbitrary code.
 924          *
 925          * @param allow {@code true} to allow, {@code false} to disallow
 926          * @return this builder
 927          */
 928         Builder allowSetThreadLocals(boolean allow);
 929 
 930         /**
 931          * Sets whether the thread inherits the initial values of {@linkplain
 932          * InheritableThreadLocal inheritable-thread-local} variables from the
 933          * constructing thread. The default is to inherit.
 934          *
 935          * <p> The initial values of {@code InheritableThreadLocal}s are never inherited
 936          * when {@link #allowSetThreadLocals(boolean)} is used to disallow the thread
 937          * to have its own copy of thread-local variables.
 938          *
 939          * @param inherit {@code true} to inherit, {@code false} to not inherit
 940          * @return this builder
 941          */
 942         Builder inheritInheritableThreadLocals(boolean inherit);
 943 
 944         /**
 945          * Sets the uncaught exception handler.
 946          * @param ueh uncaught exception handler
 947          * @return this builder
 948          */
 949         Builder uncaughtExceptionHandler(UncaughtExceptionHandler ueh);
 950 
 951         /**
 952          * Creates a new {@code Thread} from the current state of the builder to
 953          * run the given task. The {@code Thread}'s {@link Thread#start() start}
 954          * method must be invoked to schedule the thread to execute.
 955          *
 956          * @param task the object to run when the thread executes
 957          * @return a new unstarted Thread
 958          * @throws SecurityException if denied by the security manager
 959          *         (See <a href="Thread.html#ofplatform-security">Interaction with
 960          *         security manager when creating platform threads</a>)
 961          *
 962          * @see <a href="Thread.html#inheritance">Inheritance when creating threads</a>
 963          */
 964         Thread unstarted(Runnable task);
 965 
 966         /**
 967          * Creates a new {@code Thread} from the current state of the builder and
 968          * schedules it to execute.
 969          *
 970          * @param task the object to run when the thread executes
 971          * @return a new started Thread
 972          * @throws SecurityException if denied by the security manager
 973          *         (See <a href="Thread.html#ofplatform-security">Interaction with
 974          *         security manager when creating platform threads</a>)
 975          *
 976          * @see <a href="Thread.html#inheritance">Inheritance when creating threads</a>
 977          */
 978         Thread start(Runnable task);
 979 
 980         /**
 981          * Returns a {@code ThreadFactory} to create threads from the current
 982          * state of the builder. The returned thread factory is safe for use by
 983          * multiple concurrent threads.
 984          *
 985          * @return a thread factory to create threads
 986          */
 987         ThreadFactory factory();
 988 
 989         /**
 990          * A builder for creating a platform {@link Thread} or {@link ThreadFactory}
 991          * that creates platform threads.
 992          *
 993          * <p> Unless otherwise specified, passing a null argument to a method in
 994          * this interface causes a {@code NullPointerException} to be thrown.
 995          *
 996          * @see Thread#ofPlatform()
 997          * @since 19
 998          */
 999         @PreviewFeature(feature = PreviewFeature.Feature.VIRTUAL_THREADS)
1000         sealed interface OfPlatform extends Builder
1001                 permits ThreadBuilders.PlatformThreadBuilder {
1002 
1003             @Override OfPlatform name(String name);
1004 
1005             /**
1006              * @throws IllegalArgumentException {@inheritDoc}
1007              */
1008             @Override OfPlatform name(String prefix, long start);
1009 
1010             @Override OfPlatform allowSetThreadLocals(boolean allow);
1011             @Override OfPlatform inheritInheritableThreadLocals(boolean inherit);
1012             @Override OfPlatform uncaughtExceptionHandler(UncaughtExceptionHandler ueh);
1013 
1014             /**
1015              * Sets the thread group.
1016              * @param group the thread group
1017              * @return this builder
1018              */
1019             OfPlatform group(ThreadGroup group);
1020 
1021             /**
1022              * Sets the daemon status.
1023              * @param on {@code true} to create daemon threads
1024              * @return this builder
1025              */
1026             OfPlatform daemon(boolean on);
1027 
1028             /**
1029              * Sets the daemon status to {@code true}.
1030              * @implSpec The default implementation invokes {@linkplain #daemon(boolean)} with
1031              * a value of {@code true}.
1032              * @return this builder
1033              */
1034             default OfPlatform daemon() {
1035                 return daemon(true);
1036             }
1037 
1038             /**
1039              * Sets the thread priority.
1040              * @param priority priority
1041              * @return this builder
1042              * @throws IllegalArgumentException if the priority is less than
1043              *        {@link Thread#MIN_PRIORITY} or greater than {@link Thread#MAX_PRIORITY}
1044              */
1045             OfPlatform priority(int priority);
1046 
1047             /**
1048              * Sets the desired stack size.
1049              *
1050              * <p> The stack size is the approximate number of bytes of address space
1051              * that the Java virtual machine is to allocate for the thread's stack. The
1052              * effect is highly platform dependent and the Java virtual machine is free
1053              * to treat the {@code stackSize} parameter as a "suggestion". If the value
1054              * is unreasonably low for the platform then a platform specific minimum
1055              * may be used. If the value is unreasonably high then a platform specific
1056              * maximum may be used. A value of zero is always ignored.
1057              *
1058              * @param stackSize the desired stack size
1059              * @return this builder
1060              * @throws IllegalArgumentException if the stack size is negative
1061              */
1062             OfPlatform stackSize(long stackSize);
1063         }
1064 
1065         /**
1066          * A builder for creating a virtual {@link Thread} or {@link ThreadFactory}
1067          * that creates virtual threads.
1068          *
1069          * <p> Unless otherwise specified, passing a null argument to a method in
1070          * this interface causes a {@code NullPointerException} to be thrown.
1071          *
1072          * @see Thread#ofVirtual()
1073          * @since 19
1074          */
1075         @PreviewFeature(feature = PreviewFeature.Feature.VIRTUAL_THREADS)
1076         sealed interface OfVirtual extends Builder
1077                 permits ThreadBuilders.VirtualThreadBuilder {
1078 
1079             @Override OfVirtual name(String name);
1080 
1081             /**
1082              * @throws IllegalArgumentException {@inheritDoc}
1083              */
1084             @Override OfVirtual name(String prefix, long start);
1085 
1086             @Override OfVirtual allowSetThreadLocals(boolean allow);
1087             @Override OfVirtual inheritInheritableThreadLocals(boolean inherit);
1088             @Override OfVirtual uncaughtExceptionHandler(UncaughtExceptionHandler ueh);
1089         }
1090     }
1091 
1092     /**
1093      * Throws CloneNotSupportedException as a Thread can not be meaningfully
1094      * cloned. Construct a new Thread instead.
1095      *
1096      * @throws  CloneNotSupportedException
1097      *          always
1098      */
1099     @Override
1100     protected Object clone() throws CloneNotSupportedException {
1101         throw new CloneNotSupportedException();
1102     }
1103 
1104     /**
1105      * Helper class for auto-numbering platform threads. The numbers start at
1106      * 0 and are separate from the thread identifier for historical reasons.
1107      */
1108     private static class ThreadNumbering {
1109         private static final Unsafe U;
1110         private static final long NEXT;
1111         static {
1112             U = Unsafe.getUnsafe();
1113             NEXT = U.objectFieldOffset(ThreadNumbering.class, "next");
1114         }
1115         private static volatile int next;
1116         static int next() {
1117             return U.getAndAddInt(ThreadNumbering.class, NEXT, 1);
1118         }
1119     }
1120 
1121     /**
1122      * Generates a thread name of the form {@code Thread-<n>}.
1123      */
1124     static String genThreadName() {
1125         return "Thread-" + ThreadNumbering.next();
1126     }
1127 
1128     /**
1129      * Throws NullPointerException if the name is null. Avoids use of
1130      * Objects.requireNonNull in early startup.
1131      */
1132     private static String checkName(String name) {
1133         if (name == null)
1134             throw new NullPointerException("'name' is null");
1135         return name;
1136     }
1137 
1138     /**
1139      * Initializes a new platform {@code Thread}. This constructor has the same
1140      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
1141      * {@code (null, null, gname)}, where {@code gname} is a newly generated
1142      * name. Automatically generated names are of the form
1143      * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
1144      *
1145      * <p> This constructor is only useful when extending {@code Thread} to
1146      * override the {@link #run()} method.
1147      *
1148      * @see <a href="#inheritance">Inheritance when creating threads</a>
1149      */
1150     public Thread() {
1151         this(null, null, 0, null, 0, null);
1152     }
1153 
1154     /**
1155      * Initializes a new platform {@code Thread}. This constructor has the same
1156      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
1157      * {@code (null, task, gname)}, where {@code gname} is a newly generated
1158      * name. Automatically generated names are of the form
1159      * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
1160      *
1161      * <p> For a non-null task, invoking this constructor directly is equivalent to:
1162      * <pre>{@code Thread.ofPlatform().unstarted(task); }</pre>
1163      *
1164      * @param  task
1165      *         the object whose {@code run} method is invoked when this thread
1166      *         is started. If {@code null}, this classes {@code run} method does
1167      *         nothing.
1168      *
1169      * @see <a href="#inheritance">Inheritance when creating threads</a>
1170      */
1171     public Thread(Runnable task) {
1172         this(null, null, 0, task, 0, null);
1173     }
1174 
1175     /**
1176      * Creates a new Thread that inherits the given AccessControlContext
1177      * but thread-local variables are not inherited.
1178      * This is not a public constructor.
1179      */
1180     Thread(Runnable task, @SuppressWarnings("removal") AccessControlContext acc) {
1181         this(null, null, 0, task, 0, acc);
1182     }
1183 
1184     /**
1185      * Initializes a new platform {@code Thread}. This constructor has the same
1186      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
1187      * {@code (group, task, gname)}, where {@code gname} is a newly generated
1188      * name. Automatically generated names are of the form
1189      * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
1190      *
1191      * <p> For a non-null group and task, invoking this constructor directly is
1192      * equivalent to:
1193      * <pre>{@code Thread.ofPlatform().group(group).unstarted(task); }</pre>
1194      *
1195      * @param  group
1196      *         the thread group. If {@code null} and there is a security
1197      *         manager, the group is determined by {@linkplain
1198      *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
1199      *         If there is not a security manager or {@code
1200      *         SecurityManager.getThreadGroup()} returns {@code null}, the group
1201      *         is set to the current thread's thread group.
1202      *
1203      * @param  task
1204      *         the object whose {@code run} method is invoked when this thread
1205      *         is started. If {@code null}, this thread's run method is invoked.
1206      *
1207      * @throws  SecurityException
1208      *          if the current thread cannot create a thread in the specified
1209      *          thread group
1210      *
1211      * @see <a href="#inheritance">Inheritance when creating threads</a>
1212      */
1213     public Thread(ThreadGroup group, Runnable task) {
1214         this(group, null, 0, task, 0, null);
1215     }
1216 
1217     /**
1218      * Initializes a new platform {@code Thread}. This constructor has the same
1219      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
1220      * {@code (null, null, name)}.
1221      *
1222      * <p> This constructor is only useful when extending {@code Thread} to
1223      * override the {@link #run()} method.
1224      *
1225      * @param   name
1226      *          the name of the new thread
1227      *
1228      * @see <a href="#inheritance">Inheritance when creating threads</a>
1229      */
1230     public Thread(String name) {
1231         this(null, checkName(name), 0, null, 0, null);
1232     }
1233 
1234     /**
1235      * Initializes a new platform {@code Thread}. This constructor has the same
1236      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
1237      * {@code (group, null, name)}.
1238      *
1239      * <p> This constructor is only useful when extending {@code Thread} to
1240      * override the {@link #run()} method.
1241      *
1242      * @param  group
1243      *         the thread group. If {@code null} and there is a security
1244      *         manager, the group is determined by {@linkplain
1245      *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
1246      *         If there is not a security manager or {@code
1247      *         SecurityManager.getThreadGroup()} returns {@code null}, the group
1248      *         is set to the current thread's thread group.
1249      *
1250      * @param  name
1251      *         the name of the new thread
1252      *
1253      * @throws  SecurityException
1254      *          if the current thread cannot create a thread in the specified
1255      *          thread group
1256      *
1257      * @see <a href="#inheritance">Inheritance when creating threads</a>
1258      */
1259     public Thread(ThreadGroup group, String name) {
1260         this(group, checkName(name), 0, null, 0, null);
1261     }
1262 
1263     /**
1264      * Initializes a new platform {@code Thread}. This constructor has the same
1265      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
1266      * {@code (null, task, name)}.
1267      *
1268      * <p> For a non-null task and name, invoking this constructor directly is
1269      * equivalent to:
1270      * <pre>{@code Thread.ofPlatform().name(name).unstarted(task); }</pre>
1271      *
1272      * @param  task
1273      *         the object whose {@code run} method is invoked when this thread
1274      *         is started. If {@code null}, this thread's run method is invoked.
1275      *
1276      * @param  name
1277      *         the name of the new thread
1278      *
1279      * @see <a href="#inheritance">Inheritance when creating threads</a>
1280      */
1281     public Thread(Runnable task, String name) {
1282         this(null, checkName(name), 0, task, 0, null);
1283     }
1284 
1285     /**
1286      * Initializes a new platform {@code Thread} so that it has {@code task}
1287      * as its run object, has the specified {@code name} as its name,
1288      * and belongs to the thread group referred to by {@code group}.
1289      *
1290      * <p>If there is a security manager, its
1291      * {@link SecurityManager#checkAccess(ThreadGroup) checkAccess}
1292      * method is invoked with the ThreadGroup as its argument.
1293      *
1294      * <p>In addition, its {@code checkPermission} method is invoked with
1295      * the {@code RuntimePermission("enableContextClassLoaderOverride")}
1296      * permission when invoked directly or indirectly by the constructor
1297      * of a subclass which overrides the {@code getContextClassLoader}
1298      * or {@code setContextClassLoader} methods.
1299      *
1300      * <p>The priority of the newly created thread is the smaller of
1301      * priority of the thread creating it and the maximum permitted
1302      * priority of the thread group. The method {@linkplain #setPriority
1303      * setPriority} may be used to change the priority to a new value.
1304      *
1305      * <p>The newly created thread is initially marked as being a daemon
1306      * thread if and only if the thread creating it is currently marked
1307      * as a daemon thread. The method {@linkplain #setDaemon setDaemon}
1308      * may be used to change whether or not a thread is a daemon.
1309      *
1310      * <p>For a non-null group, task, and name, invoking this constructor directly
1311      * is equivalent to:
1312      * <pre>{@code Thread.ofPlatform().group(group).name(name).unstarted(task); }</pre>
1313      *
1314      * @param  group
1315      *         the thread group. If {@code null} and there is a security
1316      *         manager, the group is determined by {@linkplain
1317      *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
1318      *         If there is not a security manager or {@code
1319      *         SecurityManager.getThreadGroup()} returns {@code null}, the group
1320      *         is set to the current thread's thread group.
1321      *
1322      * @param  task
1323      *         the object whose {@code run} method is invoked when this thread
1324      *         is started. If {@code null}, this thread's run method is invoked.
1325      *
1326      * @param  name
1327      *         the name of the new thread
1328      *
1329      * @throws  SecurityException
1330      *          if the current thread cannot create a thread in the specified
1331      *          thread group or cannot override the context class loader methods.
1332      *
1333      * @see <a href="#inheritance">Inheritance when creating threads</a>
1334      */
1335     public Thread(ThreadGroup group, Runnable task, String name) {
1336         this(group, checkName(name), 0, task, 0, null);
1337     }
1338 
1339     /**
1340      * Initializes a new platform {@code Thread} so that it has {@code task}
1341      * as its run object, has the specified {@code name} as its name,
1342      * and belongs to the thread group referred to by {@code group}, and has
1343      * the specified <i>stack size</i>.
1344      *
1345      * <p>This constructor is identical to {@link
1346      * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact
1347      * that it allows the thread stack size to be specified.  The stack size
1348      * is the approximate number of bytes of address space that the virtual
1349      * machine is to allocate for this thread's stack.  <b>The effect of the
1350      * {@code stackSize} parameter, if any, is highly platform dependent.</b>
1351      *
1352      * <p>On some platforms, specifying a higher value for the
1353      * {@code stackSize} parameter may allow a thread to achieve greater
1354      * recursion depth before throwing a {@link StackOverflowError}.
1355      * Similarly, specifying a lower value may allow a greater number of
1356      * threads to exist concurrently without throwing an {@link
1357      * OutOfMemoryError} (or other internal error).  The details of
1358      * the relationship between the value of the {@code stackSize} parameter
1359      * and the maximum recursion depth and concurrency level are
1360      * platform-dependent.  <b>On some platforms, the value of the
1361      * {@code stackSize} parameter may have no effect whatsoever.</b>
1362      *
1363      * <p>The virtual machine is free to treat the {@code stackSize}
1364      * parameter as a suggestion.  If the specified value is unreasonably low
1365      * for the platform, the virtual machine may instead use some
1366      * platform-specific minimum value; if the specified value is unreasonably
1367      * high, the virtual machine may instead use some platform-specific
1368      * maximum.  Likewise, the virtual machine is free to round the specified
1369      * value up or down as it sees fit (or to ignore it completely).
1370      *
1371      * <p>Specifying a value of zero for the {@code stackSize} parameter will
1372      * cause this constructor to behave exactly like the
1373      * {@code Thread(ThreadGroup, Runnable, String)} constructor.
1374      *
1375      * <p><i>Due to the platform-dependent nature of the behavior of this
1376      * constructor, extreme care should be exercised in its use.
1377      * The thread stack size necessary to perform a given computation will
1378      * likely vary from one JRE implementation to another.  In light of this
1379      * variation, careful tuning of the stack size parameter may be required,
1380      * and the tuning may need to be repeated for each JRE implementation on
1381      * which an application is to run.</i>
1382      *
1383      * <p>Implementation note: Java platform implementers are encouraged to
1384      * document their implementation's behavior with respect to the
1385      * {@code stackSize} parameter.
1386      *
1387      * <p>For a non-null group, task, and name, invoking this constructor directly
1388      * is equivalent to:
1389      * <pre>{@code Thread.ofPlatform().group(group).name(name).stackSize(stackSize).unstarted(task); }</pre>
1390      *
1391      * @param  group
1392      *         the thread group. If {@code null} and there is a security
1393      *         manager, the group is determined by {@linkplain
1394      *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
1395      *         If there is not a security manager or {@code
1396      *         SecurityManager.getThreadGroup()} returns {@code null}, the group
1397      *         is set to the current thread's thread group.
1398      *
1399      * @param  task
1400      *         the object whose {@code run} method is invoked when this thread
1401      *         is started. If {@code null}, this thread's run method is invoked.
1402      *
1403      * @param  name
1404      *         the name of the new thread
1405      *
1406      * @param  stackSize
1407      *         the desired stack size for the new thread, or zero to indicate
1408      *         that this parameter is to be ignored.
1409      *
1410      * @throws  SecurityException
1411      *          if the current thread cannot create a thread in the specified
1412      *          thread group
1413      *
1414      * @since 1.4
1415      * @see <a href="#inheritance">Inheritance when creating threads</a>
1416      */
1417     public Thread(ThreadGroup group, Runnable task, String name, long stackSize) {
1418         this(group, checkName(name), 0, task, stackSize, null);
1419     }
1420 
1421     /**
1422      * Initializes a new platform {@code Thread} so that it has {@code task}
1423      * as its run object, has the specified {@code name} as its name,
1424      * belongs to the thread group referred to by {@code group}, has
1425      * the specified {@code stackSize}, and inherits initial values for
1426      * {@linkplain InheritableThreadLocal inheritable thread-local} variables
1427      * if {@code inheritThreadLocals} is {@code true}.
1428      *
1429      * <p> This constructor is identical to {@link
1430      * #Thread(ThreadGroup,Runnable,String,long)} with the added ability to
1431      * suppress, or not, the inheriting of initial values for inheritable
1432      * thread-local variables from the constructing thread. This allows for
1433      * finer grain control over inheritable thread-locals. Care must be taken
1434      * when passing a value of {@code false} for {@code inheritThreadLocals},
1435      * as it may lead to unexpected behavior if the new thread executes code
1436      * that expects a specific thread-local value to be inherited.
1437      *
1438      * <p> Specifying a value of {@code true} for the {@code inheritThreadLocals}
1439      * parameter will cause this constructor to behave exactly like the
1440      * {@code Thread(ThreadGroup, Runnable, String, long)} constructor.
1441      *
1442      * <p> For a non-null group, task, and name, invoking this constructor directly
1443      * is equivalent to:
1444      * <pre>{@code Thread.ofPlatform()
1445      *      .group(group)
1446      *      .name(name)
1447      *      .stackSize(stackSize)
1448      *      .inheritInheritableThreadLocals(inheritInheritableThreadLocals)
1449      *      .unstarted(task); }</pre>
1450      *
1451      * @param  group
1452      *         the thread group. If {@code null} and there is a security
1453      *         manager, the group is determined by {@linkplain
1454      *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
1455      *         If there is not a security manager or {@code
1456      *         SecurityManager.getThreadGroup()} returns {@code null}, the group
1457      *         is set to the current thread's thread group.
1458      *
1459      * @param  task
1460      *         the object whose {@code run} method is invoked when this thread
1461      *         is started. If {@code null}, this thread's run method is invoked.
1462      *
1463      * @param  name
1464      *         the name of the new thread
1465      *
1466      * @param  stackSize
1467      *         the desired stack size for the new thread, or zero to indicate
1468      *         that this parameter is to be ignored
1469      *
1470      * @param  inheritInheritableThreadLocals
1471      *         if {@code true}, inherit initial values for inheritable
1472      *         thread-locals from the constructing thread, otherwise no initial
1473      *         values are inherited
1474      *
1475      * @throws  SecurityException
1476      *          if the current thread cannot create a thread in the specified
1477      *          thread group
1478      *
1479      * @since 9
1480      * @see <a href="#inheritance">Inheritance when creating threads</a>
1481      */
1482     public Thread(ThreadGroup group, Runnable task, String name,
1483                   long stackSize, boolean inheritInheritableThreadLocals) {
1484         this(group, checkName(name),
1485                 (inheritInheritableThreadLocals ? 0 : NO_INHERIT_THREAD_LOCALS),
1486                 task, stackSize, null);
1487     }
1488 
1489     /**
1490      * Creates a virtual thread to execute a task and schedules it to execute.
1491      *
1492      * <p> This method is equivalent to:
1493      * <pre>{@code Thread.ofVirtual().start(task); }</pre>
1494      *
1495      * @param task the object to run when the thread executes
1496      * @return a new, and started, virtual thread
1497      * @throws UnsupportedOperationException if preview features are not enabled
1498      * @see <a href="#inheritance">Inheritance when creating threads</a>
1499      * @since 19
1500      */
1501     @PreviewFeature(feature = PreviewFeature.Feature.VIRTUAL_THREADS)
1502     public static Thread startVirtualThread(Runnable task) {
1503         Objects.requireNonNull(task);
1504         PreviewFeatures.ensureEnabled();
1505         var thread = ThreadBuilders.newVirtualThread(null, null, 0, task);
1506         thread.start();
1507         return thread;
1508     }
1509 
1510     /**
1511      * Returns {@code true} if this thread is a virtual thread. A virtual thread
1512      * is scheduled by the Java virtual machine rather than the operating system.
1513      *
1514      * @return {@code true} if this thread is a virtual thread
1515      *
1516      * @since 19
1517      */
1518     @PreviewFeature(feature = PreviewFeature.Feature.VIRTUAL_THREADS)
1519     public final boolean isVirtual() {
1520         return (this instanceof BaseVirtualThread);
1521     }
1522 
1523     /**
1524      * Schedules this thread to begin execution. The thread will execute
1525      * independently of the current thread.
1526      *
1527      * <p> A thread can be started at most once. In particular, a thread can not
1528      * be restarted after it has terminated.
1529      *
1530      * @throws IllegalThreadStateException if the thread was already started
1531      */
1532     public void start() {
1533         synchronized (this) {
1534             // zero status corresponds to state "NEW".
1535             if (holder.threadStatus != 0)
1536                 throw new IllegalThreadStateException();
1537             start0();
1538         }
1539     }
1540 
1541     /**
1542      * Schedules this thread to begin execution in the given thread container.
1543      * @throws IllegalStateException if the container is shutdown or closed
1544      * @throws IllegalThreadStateException if the thread has already been started
1545      */
1546     void start(ThreadContainer container) {
1547         synchronized (this) {
1548             // zero status corresponds to state "NEW".
1549             if (holder.threadStatus != 0)
1550                 throw new IllegalThreadStateException();
1551 
1552             // bind thread to container
1553             setThreadContainer(container);
1554 
1555             // start thread
1556             boolean started = false;
1557             container.onStart(this);  // may throw
1558             try {
1559                 // extent locals may be inherited
1560                 inheritExtentLocalBindings(container);
1561 
1562                 start0();
1563                 started = true;
1564             } finally {
1565                 if (!started) {
1566                     container.onExit(this);
1567                 }
1568             }
1569         }
1570     }
1571 
1572     private native void start0();
1573 
1574     /**
1575      * This method is run by the thread when it executes. Subclasses of {@code
1576      * Thread} may override this method.
1577      *
1578      * <p> This method is not intended to be invoked directly. If this thread is a
1579      * platform thread created with a {@link Runnable} task then invoking this method
1580      * will invoke the task's {@code run} method. If this thread is a virtual thread
1581      * then invoking this method directly does nothing.
1582      *
1583      * @implSpec The default implementation executes the {@link Runnable} task that
1584      * the {@code Thread} was created with. If the thread was created without a task
1585      * then this method does nothing.
1586      */
1587     @Override
1588     public void run() {
1589         Runnable task = holder.task;
1590         if (task != null) {
1591             task.run();
1592         }
1593     }
1594 
1595     /**
1596      * Null out reference after Thread termination.
1597      */
1598     void clearReferences() {
1599         threadLocals = null;
1600         inheritableThreadLocals = null;
1601         inheritedAccessControlContext = null;
1602         if (uncaughtExceptionHandler != null)
1603             uncaughtExceptionHandler = null;
1604         if (nioBlocker != null)
1605             nioBlocker = null;
1606     }
1607 
1608     /**
1609      * This method is called by the VM to give a Thread
1610      * a chance to clean up before it actually exits.
1611      */
1612     private void exit() {
1613         // pop any remaining scopes from the stack, this may block
1614         if (headStackableScopes != null) {
1615             StackableScope.popAll();
1616         }
1617 
1618         // notify container that thread is exiting
1619         ThreadContainer container = threadContainer();
1620         if (container != null) {
1621             container.onExit(this);
1622         }
1623 
1624         try {
1625             if (threadLocals != null && TerminatingThreadLocal.REGISTRY.isPresent()) {
1626                 TerminatingThreadLocal.threadTerminated();
1627             }
1628         } finally {
1629             clearReferences();
1630         }
1631     }
1632 
1633     /**
1634      * Throws {@code UnsupportedOperationException}.
1635      *
1636      * @throws  UnsupportedOperationException always
1637      *
1638      * @deprecated This method was originally specified to "stop" a victim
1639      *       thread by causing the victim thread to throw a {@link ThreadDeath}.
1640      *       It was inherently unsafe. Stopping a thread caused it to unlock
1641      *       all of the monitors that it had locked (as a natural consequence
1642      *       of the {@code ThreadDeath} exception propagating up the stack). If
1643      *       any of the objects previously protected by these monitors were in
1644      *       an inconsistent state, the damaged objects became visible to
1645      *       other threads, potentially resulting in arbitrary behavior.
1646      *       Usages of {@code stop} should be replaced by code that simply
1647      *       modifies some variable to indicate that the target thread should
1648      *       stop running.  The target thread should check this variable
1649      *       regularly, and return from its run method in an orderly fashion
1650      *       if the variable indicates that it is to stop running.  If the
1651      *       target thread waits for long periods (on a condition variable,
1652      *       for example), the {@code interrupt} method should be used to
1653      *       interrupt the wait.
1654      *       For more information, see
1655      *       <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
1656      *       are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1657      */
1658     @Deprecated(since="1.2", forRemoval=true)
1659     public final void stop() {
1660         throw new UnsupportedOperationException();
1661     }
1662 
1663     /**
1664      * Interrupts this thread.
1665      *
1666      * <p> Unless the current thread is interrupting itself, which is
1667      * always permitted, the {@link #checkAccess() checkAccess} method
1668      * of this thread is invoked, which may cause a {@link
1669      * SecurityException} to be thrown.
1670      *
1671      * <p> If this thread is blocked in an invocation of the {@link
1672      * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
1673      * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
1674      * class, or of the {@link #join()}, {@link #join(long)}, {@link
1675      * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)}
1676      * methods of this class, then its interrupt status will be cleared and it
1677      * will receive an {@link InterruptedException}.
1678      *
1679      * <p> If this thread is blocked in an I/O operation upon an {@link
1680      * java.nio.channels.InterruptibleChannel InterruptibleChannel}
1681      * then the channel will be closed, the thread's interrupt
1682      * status will be set, and the thread will receive a {@link
1683      * java.nio.channels.ClosedByInterruptException}.
1684      *
1685      * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
1686      * then the thread's interrupt status will be set and it will return
1687      * immediately from the selection operation, possibly with a non-zero
1688      * value, just as if the selector's {@link
1689      * java.nio.channels.Selector#wakeup wakeup} method were invoked.
1690      *
1691      * <p> If none of the previous conditions hold then this thread's interrupt
1692      * status will be set. </p>
1693      *
1694      * <p> Interrupting a thread that is not alive need not have any effect.
1695      *
1696      * @implNote In the JDK Reference Implementation, interruption of a thread
1697      * that is not alive still records that the interrupt request was made and
1698      * will report it via {@link #interrupted} and {@link #isInterrupted()}.
1699      *
1700      * @throws  SecurityException
1701      *          if the current thread cannot modify this thread
1702      *
1703      * @revised 6.0, 14
1704      */
1705     public void interrupt() {
1706         if (this != Thread.currentThread()) {
1707             checkAccess();
1708 
1709             // thread may be blocked in an I/O operation
1710             synchronized (interruptLock) {
1711                 Interruptible b = nioBlocker;
1712                 if (b != null) {
1713                     interrupted = true;
1714                     interrupt0();  // inform VM of interrupt
1715                     b.interrupt(this);
1716                     return;
1717                 }
1718             }
1719         }
1720         interrupted = true;
1721         interrupt0();  // inform VM of interrupt
1722     }
1723 
1724     /**
1725      * Tests whether the current thread has been interrupted.  The
1726      * <i>interrupted status</i> of the thread is cleared by this method.  In
1727      * other words, if this method were to be called twice in succession, the
1728      * second call would return false (unless the current thread were
1729      * interrupted again, after the first call had cleared its interrupted
1730      * status and before the second call had examined it).
1731      *
1732      * @return  {@code true} if the current thread has been interrupted;
1733      *          {@code false} otherwise.
1734      * @see #isInterrupted()
1735      * @revised 6.0, 14
1736      */
1737     public static boolean interrupted() {
1738         return currentThread().getAndClearInterrupt();
1739     }
1740 
1741     /**
1742      * Tests whether this thread has been interrupted.  The <i>interrupted
1743      * status</i> of the thread is unaffected by this method.
1744      *
1745      * @return  {@code true} if this thread has been interrupted;
1746      *          {@code false} otherwise.
1747      * @see     #interrupted()
1748      * @revised 6.0, 14
1749      */
1750     public boolean isInterrupted() {
1751         return interrupted;
1752     }
1753 
1754     final void setInterrupt() {
1755         // assert Thread.currentCarrierThread() == this;
1756         if (!interrupted) {
1757             interrupted = true;
1758             interrupt0();  // inform VM of interrupt
1759         }
1760     }
1761 
1762     final void clearInterrupt() {
1763         // assert Thread.currentCarrierThread() == this;
1764         if (interrupted) {
1765             interrupted = false;
1766             clearInterruptEvent();
1767         }
1768     }
1769 
1770     boolean getAndClearInterrupt() {
1771         boolean oldValue = interrupted;
1772         // We may have been interrupted the moment after we read the field,
1773         // so only clear the field if we saw that it was set and will return
1774         // true; otherwise we could lose an interrupt.
1775         if (oldValue) {
1776             interrupted = false;
1777             clearInterruptEvent();
1778         }
1779         return oldValue;
1780     }
1781 
1782     /**
1783      * Tests if this thread is alive. A thread is alive if it has
1784      * been started and has not yet terminated.
1785      *
1786      * @return  {@code true} if this thread is alive;
1787      *          {@code false} otherwise.
1788      */
1789     public final boolean isAlive() {
1790         return alive();
1791     }
1792 
1793     /**
1794      * Returns true if this thread is alive.
1795      * This method is non-final so it can be overridden.
1796      */
1797     boolean alive() {
1798         return isAlive0();
1799     }
1800     private native boolean isAlive0();
1801 
1802     /**
1803      * Throws {@code UnsupportedOperationException}.
1804      *
1805      * @throws  UnsupportedOperationException always
1806      *
1807      * @deprecated This method was originally specified to suspend a thread.
1808      *     It was inherently deadlock-prone. If the target thread held a lock on
1809      *     a monitor protecting a critical system resource when it was suspended,
1810      *     no thread could access the resource until the target thread was resumed.
1811      *     If the thread intending to resume the target thread attempted to lock
1812      *     the monitor prior to calling {@code resume}, deadlock would result.
1813      *     Such deadlocks typically manifested themselves as "frozen" processes.
1814      *     For more information, see
1815      *     <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
1816      *     are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1817      */
1818     @Deprecated(since="1.2", forRemoval=true)
1819     public final void suspend() {
1820         throw new UnsupportedOperationException();
1821     }
1822 
1823     /**
1824      * Throws {@code UnsupportedOperationException}.
1825      *
1826      * @throws  UnsupportedOperationException always
1827      *
1828      * @deprecated This method was originally specified to resume a thread
1829      *     suspended with {@link #suspend()}. Suspending a thread was
1830      *     inherently deadlock-prone.
1831      *     For more information, see
1832      *     <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
1833      *     are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1834      */
1835     @Deprecated(since="1.2", forRemoval=true)
1836     public final void resume() {
1837         throw new UnsupportedOperationException();
1838     }
1839 
1840     /**
1841      * Changes the priority of this thread.
1842      *
1843      * For platform threads, the priority is set to the smaller of the specified
1844      * {@code newPriority} and the maximum permitted priority of the thread's
1845      * {@linkplain ThreadGroup thread group}.
1846      *
1847      * The priority of a virtual thread is always {@link Thread#NORM_PRIORITY}
1848      * and {@code newPriority} is ignored.
1849      *
1850      * @param newPriority the new thread priority
1851      * @throws  IllegalArgumentException if the priority is not in the
1852      *          range {@code MIN_PRIORITY} to {@code MAX_PRIORITY}.
1853      * @throws  SecurityException
1854      *          if {@link #checkAccess} determines that the current
1855      *          thread cannot modify this thread
1856      * @see #setPriority(int)
1857      * @see ThreadGroup#getMaxPriority()
1858      */
1859     public final void setPriority(int newPriority) {
1860         checkAccess();
1861         if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
1862             throw new IllegalArgumentException();
1863         }
1864         if (!isVirtual()) {
1865             priority(newPriority);
1866         }
1867     }
1868 
1869     void priority(int newPriority) {
1870         ThreadGroup g = holder.group;
1871         if (g != null) {
1872             int maxPriority = g.getMaxPriority();
1873             if (newPriority > maxPriority) {
1874                 newPriority = maxPriority;
1875             }
1876             setPriority0(holder.priority = newPriority);
1877         }
1878     }
1879 
1880     /**
1881      * Returns this thread's priority.
1882      *
1883      * <p> The priority of a virtual thread is always {@link Thread#NORM_PRIORITY}.
1884      *
1885      * @return  this thread's priority.
1886      * @see     #setPriority
1887      */
1888     public final int getPriority() {
1889         if (isVirtual()) {
1890             return Thread.NORM_PRIORITY;
1891         } else {
1892             return holder.priority;
1893         }
1894     }
1895 
1896     /**
1897      * Changes the name of this thread to be equal to the argument {@code name}.
1898      * <p>
1899      * First the {@code checkAccess} method of this thread is called
1900      * with no arguments. This may result in throwing a
1901      * {@code SecurityException}.
1902      *
1903      * @implNote In the JDK Reference Implementation, if this thread is the
1904      * current thread, and it's a platform thread that was not attached to the
1905      * VM with the Java Native Interface
1906      * <a href="{@docRoot}/../specs/jni/invocation.html#attachcurrentthread">
1907      * AttachCurrentThread</a> function, then this method will set the operating
1908      * system thread name. This may be useful for debugging and troubleshooting
1909      * purposes.
1910      *
1911      * @param      name   the new name for this thread.
1912      * @throws     SecurityException  if the current thread cannot modify this
1913      *             thread.
1914      * @see        #getName
1915      * @see        #checkAccess()
1916      */
1917     public final synchronized void setName(String name) {
1918         checkAccess();
1919         if (name == null) {
1920             throw new NullPointerException("name cannot be null");
1921         }
1922         this.name = name;
1923         if (!isVirtual() && Thread.currentThread() == this) {
1924             setNativeName(name);
1925         }
1926     }
1927 
1928     /**
1929      * Returns this thread's name.
1930      *
1931      * @return  this thread's name.
1932      * @see     #setName(String)
1933      */
1934     public final String getName() {
1935         return name;
1936     }
1937 
1938     /**
1939      * Returns the thread's thread group or {@code null} if the thread has
1940      * terminated.
1941      *
1942      * <p> The thread group returned for a virtual thread is the special
1943      * <a href="ThreadGroup.html#virtualthreadgroup"><em>ThreadGroup for
1944      * virtual threads</em></a>.
1945      *
1946      * @return  this thread's thread group or {@code null}
1947      */
1948     public final ThreadGroup getThreadGroup() {
1949         if (isTerminated()) {
1950             return null;
1951         } else {
1952             return isVirtual() ? virtualThreadGroup() : holder.group;
1953         }
1954     }
1955 
1956     /**
1957      * Returns an estimate of the number of {@linkplain #isAlive() live}
1958      * platform threads in the current thread's thread group and its subgroups.
1959      * Virtual threads are not included in the estimate.
1960      *
1961      * <p> The value returned is only an estimate because the number of
1962      * threads may change dynamically while this method traverses internal
1963      * data structures, and might be affected by the presence of certain
1964      * system threads. This method is intended primarily for debugging
1965      * and monitoring purposes.
1966      *
1967      * @return  an estimate of the number of live platform threads in the
1968      *          current thread's thread group and in any other thread group
1969      *          that has the current thread's thread group as an ancestor
1970      */
1971     public static int activeCount() {
1972         return currentThread().getThreadGroup().activeCount();
1973     }
1974 
1975     /**
1976      * Copies into the specified array every {@linkplain #isAlive() live}
1977      * platform thread in the current thread's thread group and its subgroups.
1978      * This method simply invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])}
1979      * method of the current thread's thread group. Virtual threads are
1980      * not enumerated by this method.
1981      *
1982      * <p> An application might use the {@linkplain #activeCount activeCount}
1983      * method to get an estimate of how big the array should be, however
1984      * <i>if the array is too short to hold all the threads, the extra threads
1985      * are silently ignored.</i>  If it is critical to obtain every live
1986      * thread in the current thread's thread group and its subgroups, the
1987      * invoker should verify that the returned int value is strictly less
1988      * than the length of {@code tarray}.
1989      *
1990      * <p> Due to the inherent race condition in this method, it is recommended
1991      * that the method only be used for debugging and monitoring purposes.
1992      *
1993      * @param  tarray
1994      *         an array into which to put the list of threads
1995      *
1996      * @return  the number of threads put into the array
1997      *
1998      * @throws  SecurityException
1999      *          if {@link java.lang.ThreadGroup#checkAccess} determines that
2000      *          the current thread cannot access its thread group
2001      */
2002     public static int enumerate(Thread[] tarray) {
2003         return currentThread().getThreadGroup().enumerate(tarray);
2004     }
2005 
2006     /**
2007      * Throws {@code UnsupportedOperationException}.
2008      *
2009      * @return     nothing
2010      *
2011      * @deprecated This method was originally designed to count the number of
2012      *             stack frames but the results were never well-defined and it
2013      *             depended on thread-suspension.
2014      *             This method is subject to removal in a future version of Java SE.
2015      * @see        StackWalker
2016      */
2017     @Deprecated(since="1.2", forRemoval=true)
2018     public int countStackFrames() {
2019         throw new UnsupportedOperationException();
2020     }
2021 
2022     /**
2023      * Waits at most {@code millis} milliseconds for this thread to terminate.
2024      * A timeout of {@code 0} means to wait forever.
2025      * This method returns immediately, without waiting, if the thread has not
2026      * been {@link #start() started}.
2027      *
2028      * @implNote
2029      * For platform threads, the implementation uses a loop of {@code this.wait}
2030      * calls conditioned on {@code this.isAlive}. As a thread terminates the
2031      * {@code this.notifyAll} method is invoked. It is recommended that
2032      * applications not use {@code wait}, {@code notify}, or
2033      * {@code notifyAll} on {@code Thread} instances.
2034      *
2035      * @param  millis
2036      *         the time to wait in milliseconds
2037      *
2038      * @throws  IllegalArgumentException
2039      *          if the value of {@code millis} is negative
2040      *
2041      * @throws  InterruptedException
2042      *          if any thread has interrupted the current thread. The
2043      *          <i>interrupted status</i> of the current thread is
2044      *          cleared when this exception is thrown.
2045      */
2046     public final void join(long millis) throws InterruptedException {
2047         if (millis < 0)
2048             throw new IllegalArgumentException("timeout value is negative");
2049 
2050         if (this instanceof VirtualThread vthread) {
2051             if (isAlive()) {
2052                 long nanos = MILLISECONDS.toNanos(millis);
2053                 vthread.joinNanos(nanos);
2054             }
2055             return;
2056         }
2057 
2058         synchronized (this) {
2059             if (millis > 0) {
2060                 if (isAlive()) {
2061                     final long startTime = System.nanoTime();
2062                     long delay = millis;
2063                     do {
2064                         wait(delay);
2065                     } while (isAlive() && (delay = millis -
2066                              NANOSECONDS.toMillis(System.nanoTime() - startTime)) > 0);
2067                 }
2068             } else {
2069                 while (isAlive()) {
2070                     wait(0);
2071                 }
2072             }
2073         }
2074     }
2075 
2076     /**
2077      * Waits at most {@code millis} milliseconds plus
2078      * {@code nanos} nanoseconds for this thread to terminate.
2079      * If both arguments are {@code 0}, it means to wait forever.
2080      * This method returns immediately, without waiting, if the thread has not
2081      * been {@link #start() started}.
2082      *
2083      * @implNote
2084      * For platform threads, the implementation uses a loop of {@code this.wait}
2085      * calls conditioned on {@code this.isAlive}. As a thread terminates the
2086      * {@code this.notifyAll} method is invoked. It is recommended that
2087      * applications not use {@code wait}, {@code notify}, or
2088      * {@code notifyAll} on {@code Thread} instances.
2089      *
2090      * @param  millis
2091      *         the time to wait in milliseconds
2092      *
2093      * @param  nanos
2094      *         {@code 0-999999} additional nanoseconds to wait
2095      *
2096      * @throws  IllegalArgumentException
2097      *          if the value of {@code millis} is negative, or the value
2098      *          of {@code nanos} is not in the range {@code 0-999999}
2099      *
2100      * @throws  InterruptedException
2101      *          if any thread has interrupted the current thread. The
2102      *          <i>interrupted status</i> of the current thread is
2103      *          cleared when this exception is thrown.
2104      */
2105     public final void join(long millis, int nanos) throws InterruptedException {
2106         if (millis < 0) {
2107             throw new IllegalArgumentException("timeout value is negative");
2108         }
2109 
2110         if (nanos < 0 || nanos > 999999) {
2111             throw new IllegalArgumentException("nanosecond timeout value out of range");
2112         }
2113 
2114         if (this instanceof VirtualThread vthread) {
2115             if (isAlive()) {
2116                 // convert arguments to a total in nanoseconds
2117                 long totalNanos = MILLISECONDS.toNanos(millis);
2118                 totalNanos += Math.min(Long.MAX_VALUE - totalNanos, nanos);
2119                 vthread.joinNanos(totalNanos);
2120             }
2121             return;
2122         }
2123 
2124         if (nanos > 0 && millis < Long.MAX_VALUE) {
2125             millis++;
2126         }
2127         join(millis);
2128     }
2129 
2130     /**
2131      * Waits for this thread to terminate.
2132      *
2133      * <p> An invocation of this method behaves in exactly the same
2134      * way as the invocation
2135      *
2136      * <blockquote>
2137      * {@linkplain #join(long) join}{@code (0)}
2138      * </blockquote>
2139      *
2140      * @throws  InterruptedException
2141      *          if any thread has interrupted the current thread. The
2142      *          <i>interrupted status</i> of the current thread is
2143      *          cleared when this exception is thrown.
2144      */
2145     public final void join() throws InterruptedException {
2146         join(0);
2147     }
2148 
2149     /**
2150      * Waits for this thread to terminate for up to the given waiting duration.
2151      *
2152      * <p> This method does not wait if the duration to wait is less than or
2153      * equal to zero. In this case, the method just tests if the thread has
2154      * terminated.
2155      *
2156      * @param   duration
2157      *          the maximum duration to wait
2158      *
2159      * @return  {@code true} if the thread has terminated, {@code false} if the
2160      *          thread has not terminated
2161      *
2162      * @throws  InterruptedException
2163      *          if the current thread is interrupted while waiting.
2164      *          The <i>interrupted status</i> of the current thread is cleared
2165      *          when this exception is thrown.
2166      *
2167      * @throws  IllegalThreadStateException
2168      *          if this thread has not been started.
2169      *
2170      * @since 19
2171      */
2172     public final boolean join(Duration duration) throws InterruptedException {
2173         long nanos = NANOSECONDS.convert(duration); // MAX_VALUE if > 292 years
2174 
2175         Thread.State state = threadState();
2176         if (state == State.NEW)
2177             throw new IllegalThreadStateException("Thread not started");
2178         if (state == State.TERMINATED)
2179             return true;
2180         if (nanos <= 0)
2181             return false;
2182 
2183         if (this instanceof VirtualThread vthread) {
2184             return vthread.joinNanos(nanos);
2185         }
2186 
2187         // convert to milliseconds
2188         long millis = MILLISECONDS.convert(nanos, NANOSECONDS);
2189         if (nanos > NANOSECONDS.convert(millis, MILLISECONDS)) {
2190             millis += 1L;
2191         }
2192         join(millis);
2193         return isTerminated();
2194     }
2195 
2196     /**
2197      * Prints a stack trace of the current thread to the standard error stream.
2198      * This method is useful for debugging.
2199      */
2200     public static void dumpStack() {
2201         new Exception("Stack trace").printStackTrace();
2202     }
2203 
2204     /**
2205      * Marks this thread as either a <i>daemon</i> or <i>non-daemon</i> thread.
2206      * The <a href="Runtime.html#shutdown">shutdown sequence</a> begins when all
2207      * started non-daemon threads have terminated.
2208      *
2209      * <p> The daemon status of a virtual thread is always {@code true} and cannot be
2210      * changed by this method to {@code false}.
2211      *
2212      * <p> This method must be invoked before the thread is started. The behavior
2213      * of this method when the thread has terminated is not specified.
2214      *
2215      * @param  on
2216      *         if {@code true}, marks this thread as a daemon thread
2217      *
2218      * @throws  IllegalArgumentException
2219      *          if this is a virtual thread and {@code on} is false
2220      * @throws  IllegalThreadStateException
2221      *          if this thread is {@linkplain #isAlive alive}
2222      * @throws  SecurityException
2223      *          if {@link #checkAccess} determines that the current
2224      *          thread cannot modify this thread
2225      */
2226     public final void setDaemon(boolean on) {
2227         checkAccess();
2228         if (isVirtual() && !on)
2229             throw new IllegalArgumentException("'false' not legal for virtual threads");
2230         if (isAlive())
2231             throw new IllegalThreadStateException();
2232         if (!isVirtual())
2233             daemon(on);
2234     }
2235 
2236     void daemon(boolean on) {
2237         holder.daemon = on;
2238     }
2239 
2240     /**
2241      * Tests if this thread is a daemon thread.
2242      * The daemon status of a virtual thread is always {@code true}.
2243      *
2244      * @return  {@code true} if this thread is a daemon thread;
2245      *          {@code false} otherwise.
2246      * @see     #setDaemon(boolean)
2247      */
2248     public final boolean isDaemon() {
2249         if (isVirtual()) {
2250             return true;
2251         } else {
2252             return holder.daemon;
2253         }
2254     }
2255 
2256     /**
2257      * Determines if the currently running thread has permission to
2258      * modify this thread.
2259      * <p>
2260      * If there is a security manager, its {@code checkAccess} method
2261      * is called with this thread as its argument. This may result in
2262      * throwing a {@code SecurityException}.
2263      *
2264      * @throws  SecurityException  if the current thread is not allowed to
2265      *          access this thread.
2266      * @see        SecurityManager#checkAccess(Thread)
2267      * @deprecated This method is only useful in conjunction with
2268      *       {@linkplain SecurityManager the Security Manager}, which is
2269      *       deprecated and subject to removal in a future release.
2270      *       Consequently, this method is also deprecated and subject to
2271      *       removal. There is no replacement for the Security Manager or this
2272      *       method.
2273      */
2274     @Deprecated(since="17", forRemoval=true)
2275     public final void checkAccess() {
2276         @SuppressWarnings("removal")
2277         SecurityManager security = System.getSecurityManager();
2278         if (security != null) {
2279             security.checkAccess(this);
2280         }
2281     }
2282 
2283     /**
2284      * Returns a string representation of this thread. The string representation
2285      * will usually include the thread's {@linkplain #threadId() identifier} and
2286      * name. The default implementation for platform threads includes the thread's
2287      * identifier, name, priority, and the name of the thread group.
2288      *
2289      * @return  a string representation of this thread.
2290      */
2291     public String toString() {
2292         StringBuilder sb = new StringBuilder("Thread[#");
2293         sb.append(threadId());
2294         sb.append(",");
2295         sb.append(getName());
2296         sb.append(",");
2297         sb.append(getPriority());
2298         sb.append(",");
2299         ThreadGroup group = getThreadGroup();
2300         if (group != null)
2301             sb.append(group.getName());
2302         sb.append("]");
2303         return sb.toString();
2304     }
2305 
2306     /**
2307      * Returns the context {@code ClassLoader} for this thread.
2308      * The context {@code ClassLoader} may be set by the creator of the thread
2309      * for use by code running in this thread when loading classes and resources.
2310      * If not {@linkplain #setContextClassLoader set}, the default is to inherit
2311      * the context class loader from the parent thread.
2312      *
2313      * <p> The context {@code ClassLoader} of the primordial thread is typically
2314      * set to the class loader used to load the application.
2315      *
2316      * @return  the context {@code ClassLoader} for this thread, or {@code null}
2317      *          indicating the system class loader (or, failing that, the
2318      *          bootstrap class loader)
2319      *
2320      * @throws  SecurityException
2321      *          if a security manager is present, and the caller's class loader
2322      *          is not {@code null} and is not the same as or an ancestor of the
2323      *          context class loader, and the caller does not have the
2324      *          {@link RuntimePermission}{@code ("getClassLoader")}
2325      *
2326      * @since 1.2
2327      */
2328     @CallerSensitive
2329     public ClassLoader getContextClassLoader() {
2330         ClassLoader cl = this.contextClassLoader;
2331         if (cl == null)
2332             return null;
2333         if (!isSupportedClassLoader(cl))
2334             cl = ClassLoader.getSystemClassLoader();
2335         @SuppressWarnings("removal")
2336         SecurityManager sm = System.getSecurityManager();
2337         if (sm != null) {
2338             Class<?> caller = Reflection.getCallerClass();
2339             ClassLoader.checkClassLoaderPermission(cl, caller);
2340         }
2341         return cl;
2342     }
2343 
2344     /**
2345      * Sets the context {@code ClassLoader} for this thread.
2346      *
2347      * <p> The context {@code ClassLoader} may be set by the creator of the thread
2348      * for use by code running in this thread when loading classes and resources.
2349      *
2350      * <p> The context {@code ClassLoader} cannot be set when the thread is
2351      * {@linkplain Thread.Builder#allowSetThreadLocals(boolean) not allowed} to have
2352      * its own copy of thread local variables.
2353      *
2354      * <p> If a security manager is present, its {@link
2355      * SecurityManager#checkPermission(java.security.Permission) checkPermission}
2356      * method is invoked with a {@link RuntimePermission RuntimePermission}{@code
2357      * ("setContextClassLoader")} permission to see if setting the context
2358      * ClassLoader is permitted.
2359      *
2360      * @param  cl
2361      *         the context ClassLoader for this Thread, or null  indicating the
2362      *         system class loader (or, failing that, the bootstrap class loader)
2363      *
2364      * @throws  UnsupportedOperationException if this thread is not allowed
2365      *          to set values for its copy of thread-local variables
2366      *
2367      * @throws  SecurityException
2368      *          if the current thread cannot set the context ClassLoader
2369      *
2370      * @since 1.2
2371      */
2372     public void setContextClassLoader(ClassLoader cl) {
2373         @SuppressWarnings("removal")
2374         SecurityManager sm = System.getSecurityManager();
2375         if (sm != null) {
2376             sm.checkPermission(new RuntimePermission("setContextClassLoader"));
2377         }
2378         if (!isSupportedClassLoader(contextClassLoader)) {
2379             throw new UnsupportedOperationException(
2380                 "The context class loader cannot be set");
2381         }
2382         contextClassLoader = cl;
2383     }
2384 
2385     /**
2386      * Returns true if the given ClassLoader is a "supported" class loader. All
2387      * class loaders, except ClassLoaders.NOT_SUPPORTED, are considered supported.
2388      * This method allows the initialization of ClassLoaders to be delayed until
2389      * it is required.
2390      */
2391     private static boolean isSupportedClassLoader(ClassLoader loader) {
2392         if (loader == null)
2393             return true;
2394         if (loader == jdk.internal.loader.ClassLoaders.appClassLoader())
2395             return true;
2396         return loader != Constants.NOT_SUPPORTED_CLASSLOADER;
2397     }
2398 
2399     /**
2400      * Returns {@code true} if and only if the current thread holds the
2401      * monitor lock on the specified object.
2402      *
2403      * <p>This method is designed to allow a program to assert that
2404      * the current thread already holds a specified lock:
2405      * <pre>
2406      *     assert Thread.holdsLock(obj);
2407      * </pre>
2408      *
2409      * @param  obj the object on which to test lock ownership
2410      * @return {@code true} if the current thread holds the monitor lock on
2411      *         the specified object.
2412      * @since 1.4
2413      */
2414     public static native boolean holdsLock(Object obj);
2415 
2416     private static final StackTraceElement[] EMPTY_STACK_TRACE
2417         = new StackTraceElement[0];
2418 
2419     /**
2420      * Returns an array of stack trace elements representing the stack dump
2421      * of this thread.  This method will return a zero-length array if
2422      * this thread has not started, has started but has not yet been
2423      * scheduled to run by the system, or has terminated.
2424      * If the returned array is of non-zero length then the first element of
2425      * the array represents the top of the stack, which is the most recent
2426      * method invocation in the sequence.  The last element of the array
2427      * represents the bottom of the stack, which is the least recent method
2428      * invocation in the sequence.
2429      *
2430      * <p>If there is a security manager, and this thread is not
2431      * the current thread, then the security manager's
2432      * {@code checkPermission} method is called with a
2433      * {@code RuntimePermission("getStackTrace")} permission
2434      * to see if it's ok to get the stack trace.
2435      *
2436      * <p>Some virtual machines may, under some circumstances, omit one
2437      * or more stack frames from the stack trace.  In the extreme case,
2438      * a virtual machine that has no stack trace information concerning
2439      * this thread is permitted to return a zero-length array from this
2440      * method.
2441      *
2442      * @return an array of {@code StackTraceElement},
2443      * each represents one stack frame.
2444      *
2445      * @throws SecurityException
2446      *        if a security manager exists and its
2447      *        {@code checkPermission} method doesn't allow
2448      *        getting the stack trace of thread.
2449      * @see Throwable#getStackTrace
2450      *
2451      * @since 1.5
2452      */
2453     public StackTraceElement[] getStackTrace() {
2454         if (this != Thread.currentThread()) {
2455             // check for getStackTrace permission
2456             @SuppressWarnings("removal")
2457             SecurityManager security = System.getSecurityManager();
2458             if (security != null) {
2459                 security.checkPermission(SecurityConstants.GET_STACK_TRACE_PERMISSION);
2460             }
2461             // optimization so we do not call into the vm for threads that
2462             // have not yet started or have terminated
2463             if (!isAlive()) {
2464                 return EMPTY_STACK_TRACE;
2465             }
2466             StackTraceElement[] stackTrace = asyncGetStackTrace();
2467             return (stackTrace != null) ? stackTrace : EMPTY_STACK_TRACE;
2468         } else {
2469             return (new Exception()).getStackTrace();
2470         }
2471     }
2472 
2473     /**
2474      * Returns an array of stack trace elements representing the stack dump of
2475      * this thread. Returns null if the stack trace cannot be obtained. In
2476      * the default implementation, null is returned if the thread is a virtual
2477      * thread that is not mounted or the thread is a platform thread that has
2478      * terminated.
2479      */
2480     StackTraceElement[] asyncGetStackTrace() {
2481         Object stackTrace = getStackTrace0();
2482         if (stackTrace == null) {
2483             return null;
2484         }
2485         StackTraceElement[] stes = (StackTraceElement[]) stackTrace;
2486         if (stes.length == 0) {
2487             return null;
2488         } else {
2489             return StackTraceElement.of(stes);
2490         }
2491     }
2492 
2493     private native Object getStackTrace0();
2494 
2495     /**
2496      * Returns a map of stack traces for all live platform threads. The map
2497      * does not include virtual threads.
2498      * The map keys are threads and each map value is an array of
2499      * {@code StackTraceElement} that represents the stack dump
2500      * of the corresponding {@code Thread}.
2501      * The returned stack traces are in the format specified for
2502      * the {@link #getStackTrace getStackTrace} method.
2503      *
2504      * <p>The threads may be executing while this method is called.
2505      * The stack trace of each thread only represents a snapshot and
2506      * each stack trace may be obtained at different time.  A zero-length
2507      * array will be returned in the map value if the virtual machine has
2508      * no stack trace information about a thread.
2509      *
2510      * <p>If there is a security manager, then the security manager's
2511      * {@code checkPermission} method is called with a
2512      * {@code RuntimePermission("getStackTrace")} permission as well as
2513      * {@code RuntimePermission("modifyThreadGroup")} permission
2514      * to see if it is ok to get the stack trace of all threads.
2515      *
2516      * @return a {@code Map} from {@code Thread} to an array of
2517      * {@code StackTraceElement} that represents the stack trace of
2518      * the corresponding thread.
2519      *
2520      * @throws SecurityException
2521      *        if a security manager exists and its
2522      *        {@code checkPermission} method doesn't allow
2523      *        getting the stack trace of thread.
2524      * @see #getStackTrace
2525      * @see Throwable#getStackTrace
2526      *
2527      * @since 1.5
2528      */
2529     public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
2530         // check for getStackTrace permission
2531         @SuppressWarnings("removal")
2532         SecurityManager security = System.getSecurityManager();
2533         if (security != null) {
2534             security.checkPermission(SecurityConstants.GET_STACK_TRACE_PERMISSION);
2535             security.checkPermission(SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
2536         }
2537 
2538         // Get a snapshot of the list of all threads
2539         Thread[] threads = getThreads();
2540         StackTraceElement[][] traces = dumpThreads(threads);
2541         Map<Thread, StackTraceElement[]> m = HashMap.newHashMap(threads.length);
2542         for (int i = 0; i < threads.length; i++) {
2543             Thread thread = threads[i];
2544             StackTraceElement[] stackTrace = traces[i];
2545             // BoundVirtualThread objects may be in list returned by the VM
2546             if (!thread.isVirtual() && stackTrace != null) {
2547                 m.put(threads[i], stackTrace);
2548             }
2549             // else terminated so we don't put it in the map
2550         }
2551         return m;
2552     }
2553 
2554     /** cache of subclass security audit results */
2555     private static class Caches {
2556         /** cache of subclass security audit results */
2557         static final ClassValue<Boolean> subclassAudits =
2558             new ClassValue<>() {
2559                 @Override
2560                 protected Boolean computeValue(Class<?> type) {
2561                     return auditSubclass(type);
2562                 }
2563             };
2564     }
2565 
2566     /**
2567      * Verifies that this (possibly subclass) instance can be constructed
2568      * without violating security constraints: the subclass must not override
2569      * security-sensitive non-final methods, or else the
2570      * "enableContextClassLoaderOverride" RuntimePermission is checked.
2571      */
2572     private static boolean isCCLOverridden(Class<?> cl) {
2573         if (cl == Thread.class)
2574             return false;
2575 
2576         return Caches.subclassAudits.get(cl);
2577     }
2578 
2579     /**
2580      * Performs reflective checks on given subclass to verify that it doesn't
2581      * override security-sensitive non-final methods.  Returns true if the
2582      * subclass overrides any of the methods, false otherwise.
2583      */
2584     private static boolean auditSubclass(final Class<?> subcl) {
2585         @SuppressWarnings("removal")
2586         Boolean result = AccessController.doPrivileged(
2587             new PrivilegedAction<>() {
2588                 public Boolean run() {
2589                     for (Class<?> cl = subcl;
2590                          cl != Thread.class;
2591                          cl = cl.getSuperclass())
2592                     {
2593                         try {
2594                             cl.getDeclaredMethod("getContextClassLoader", new Class<?>[0]);
2595                             return Boolean.TRUE;
2596                         } catch (NoSuchMethodException ex) {
2597                         }
2598                         try {
2599                             Class<?>[] params = {ClassLoader.class};
2600                             cl.getDeclaredMethod("setContextClassLoader", params);
2601                             return Boolean.TRUE;
2602                         } catch (NoSuchMethodException ex) {
2603                         }
2604                     }
2605                     return Boolean.FALSE;
2606                 }
2607             }
2608         );
2609         return result.booleanValue();
2610     }
2611 
2612     /**
2613      * Return an array of all live threads.
2614      */
2615     static Thread[] getAllThreads() {
2616         Thread[] threads = getThreads();
2617         return Stream.of(threads)
2618                 // BoundVirtualThread objects may be in list returned by the VM
2619                 .filter(Predicate.not(Thread::isVirtual))
2620                 .toArray(Thread[]::new);
2621     }
2622 
2623     private static native StackTraceElement[][] dumpThreads(Thread[] threads);
2624     private static native Thread[] getThreads();
2625 
2626     /**
2627      * Returns the identifier of this Thread.  The thread ID is a positive
2628      * {@code long} number generated when this thread was created.
2629      * The thread ID is unique and remains unchanged during its lifetime.
2630      *
2631      * @return this thread's ID
2632      *
2633      * @deprecated This method is not final and may be overridden to return a
2634      * value that is not the thread ID. Use {@link #threadId()} instead.
2635      *
2636      * @since 1.5
2637      */
2638     @Deprecated(since="19")
2639     public long getId() {
2640         return threadId();
2641     }
2642 
2643     /**
2644      * Returns the identifier of this Thread.  The thread ID is a positive
2645      * {@code long} number generated when this thread was created.
2646      * The thread ID is unique and remains unchanged during its lifetime.
2647      *
2648      * @return this thread's ID
2649      * @since 19
2650      */
2651     public final long threadId() {
2652         return tid;
2653     }
2654 
2655     /**
2656      * A thread state.  A thread can be in one of the following states:
2657      * <ul>
2658      * <li>{@link #NEW}<br>
2659      *     A thread that has not yet started is in this state.
2660      *     </li>
2661      * <li>{@link #RUNNABLE}<br>
2662      *     A thread executing in the Java virtual machine is in this state.
2663      *     </li>
2664      * <li>{@link #BLOCKED}<br>
2665      *     A thread that is blocked waiting for a monitor lock
2666      *     is in this state.
2667      *     </li>
2668      * <li>{@link #WAITING}<br>
2669      *     A thread that is waiting indefinitely for another thread to
2670      *     perform a particular action is in this state.
2671      *     </li>
2672      * <li>{@link #TIMED_WAITING}<br>
2673      *     A thread that is waiting for another thread to perform an action
2674      *     for up to a specified waiting time is in this state.
2675      *     </li>
2676      * <li>{@link #TERMINATED}<br>
2677      *     A thread that has exited is in this state.
2678      *     </li>
2679      * </ul>
2680      *
2681      * <p>
2682      * A thread can be in only one state at a given point in time.
2683      * These states are virtual machine states which do not reflect
2684      * any operating system thread states.
2685      *
2686      * @since   1.5
2687      * @see #getState
2688      */
2689     public enum State {
2690         /**
2691          * Thread state for a thread which has not yet started.
2692          */
2693         NEW,
2694 
2695         /**
2696          * Thread state for a runnable thread.  A thread in the runnable
2697          * state is executing in the Java virtual machine but it may
2698          * be waiting for other resources from the operating system
2699          * such as processor.
2700          */
2701         RUNNABLE,
2702 
2703         /**
2704          * Thread state for a thread blocked waiting for a monitor lock.
2705          * A thread in the blocked state is waiting for a monitor lock
2706          * to enter a synchronized block/method or
2707          * reenter a synchronized block/method after calling
2708          * {@link Object#wait() Object.wait}.
2709          */
2710         BLOCKED,
2711 
2712         /**
2713          * Thread state for a waiting thread.
2714          * A thread is in the waiting state due to calling one of the
2715          * following methods:
2716          * <ul>
2717          *   <li>{@link Object#wait() Object.wait} with no timeout</li>
2718          *   <li>{@link #join() Thread.join} with no timeout</li>
2719          *   <li>{@link LockSupport#park() LockSupport.park}</li>
2720          * </ul>
2721          *
2722          * <p>A thread in the waiting state is waiting for another thread to
2723          * perform a particular action.
2724          *
2725          * For example, a thread that has called {@code Object.wait()}
2726          * on an object is waiting for another thread to call
2727          * {@code Object.notify()} or {@code Object.notifyAll()} on
2728          * that object. A thread that has called {@code Thread.join()}
2729          * is waiting for a specified thread to terminate.
2730          */
2731         WAITING,
2732 
2733         /**
2734          * Thread state for a waiting thread with a specified waiting time.
2735          * A thread is in the timed waiting state due to calling one of
2736          * the following methods with a specified positive waiting time:
2737          * <ul>
2738          *   <li>{@link #sleep Thread.sleep}</li>
2739          *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
2740          *   <li>{@link #join(long) Thread.join} with timeout</li>
2741          *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
2742          *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
2743          * </ul>
2744          */
2745         TIMED_WAITING,
2746 
2747         /**
2748          * Thread state for a terminated thread.
2749          * The thread has completed execution.
2750          */
2751         TERMINATED;
2752     }
2753 
2754     /**
2755      * Returns the state of this thread.
2756      * This method is designed for use in monitoring of the system state,
2757      * not for synchronization control.
2758      *
2759      * @return this thread's state.
2760      * @since 1.5
2761      */
2762     public State getState() {
2763         return threadState();
2764     }
2765 
2766     /**
2767      * Returns the state of this thread.
2768      * This method can be used instead of getState as getState is not final and
2769      * so can be overridden to run arbitrary code.
2770      */
2771     State threadState() {
2772         return jdk.internal.misc.VM.toThreadState(holder.threadStatus);
2773     }
2774 
2775     /**
2776      * Returns true if the thread has terminated.
2777      */
2778     boolean isTerminated() {
2779         return threadState() == State.TERMINATED;
2780     }
2781 
2782     /**
2783      * Interface for handlers invoked when a {@code Thread} abruptly
2784      * terminates due to an uncaught exception.
2785      * <p>When a thread is about to terminate due to an uncaught exception
2786      * the Java Virtual Machine will query the thread for its
2787      * {@code UncaughtExceptionHandler} using
2788      * {@link #getUncaughtExceptionHandler} and will invoke the handler's
2789      * {@code uncaughtException} method, passing the thread and the
2790      * exception as arguments.
2791      * If a thread has not had its {@code UncaughtExceptionHandler}
2792      * explicitly set, then its {@code ThreadGroup} object acts as its
2793      * {@code UncaughtExceptionHandler}. If the {@code ThreadGroup} object
2794      * has no
2795      * special requirements for dealing with the exception, it can forward
2796      * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
2797      * default uncaught exception handler}.
2798      *
2799      * @see #setDefaultUncaughtExceptionHandler
2800      * @see #setUncaughtExceptionHandler
2801      * @see ThreadGroup#uncaughtException
2802      * @since 1.5
2803      */
2804     @FunctionalInterface
2805     public interface UncaughtExceptionHandler {
2806         /**
2807          * Method invoked when the given thread terminates due to the
2808          * given uncaught exception.
2809          * <p>Any exception thrown by this method will be ignored by the
2810          * Java Virtual Machine.
2811          * @param t the thread
2812          * @param e the exception
2813          */
2814         void uncaughtException(Thread t, Throwable e);
2815     }
2816 
2817     // null unless explicitly set
2818     private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
2819 
2820     // null unless explicitly set
2821     private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
2822 
2823     /**
2824      * Set the default handler invoked when a thread abruptly terminates
2825      * due to an uncaught exception, and no other handler has been defined
2826      * for that thread.
2827      *
2828      * <p>Uncaught exception handling is controlled first by the thread, then
2829      * by the thread's {@link ThreadGroup} object and finally by the default
2830      * uncaught exception handler. If the thread does not have an explicit
2831      * uncaught exception handler set, and the thread's thread group
2832      * (including parent thread groups)  does not specialize its
2833      * {@code uncaughtException} method, then the default handler's
2834      * {@code uncaughtException} method will be invoked.
2835      * <p>By setting the default uncaught exception handler, an application
2836      * can change the way in which uncaught exceptions are handled (such as
2837      * logging to a specific device, or file) for those threads that would
2838      * already accept whatever &quot;default&quot; behavior the system
2839      * provided.
2840      *
2841      * <p>Note that the default uncaught exception handler should not usually
2842      * defer to the thread's {@code ThreadGroup} object, as that could cause
2843      * infinite recursion.
2844      *
2845      * @param ueh the object to use as the default uncaught exception handler.
2846      * If {@code null} then there is no default handler.
2847      *
2848      * @throws SecurityException if a security manager is present and it denies
2849      *         {@link RuntimePermission}{@code ("setDefaultUncaughtExceptionHandler")}
2850      *
2851      * @see #setUncaughtExceptionHandler
2852      * @see #getUncaughtExceptionHandler
2853      * @see ThreadGroup#uncaughtException
2854      * @since 1.5
2855      */
2856     public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
2857         @SuppressWarnings("removal")
2858         SecurityManager sm = System.getSecurityManager();
2859         if (sm != null) {
2860             sm.checkPermission(
2861                 new RuntimePermission("setDefaultUncaughtExceptionHandler"));
2862         }
2863         defaultUncaughtExceptionHandler = ueh;
2864     }
2865 
2866     /**
2867      * Returns the default handler invoked when a thread abruptly terminates
2868      * due to an uncaught exception. If the returned value is {@code null},
2869      * there is no default.
2870      * @since 1.5
2871      * @see #setDefaultUncaughtExceptionHandler
2872      * @return the default uncaught exception handler for all threads
2873      */
2874     public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
2875         return defaultUncaughtExceptionHandler;
2876     }
2877 
2878     /**
2879      * Returns the handler invoked when this thread abruptly terminates
2880      * due to an uncaught exception. If this thread has not had an
2881      * uncaught exception handler explicitly set then this thread's
2882      * {@code ThreadGroup} object is returned, unless this thread
2883      * has terminated, in which case {@code null} is returned.
2884      * @since 1.5
2885      * @return the uncaught exception handler for this thread
2886      */
2887     public UncaughtExceptionHandler getUncaughtExceptionHandler() {
2888         if (isTerminated()) {
2889             // uncaughtExceptionHandler may be set to null after thread terminates
2890             return null;
2891         } else {
2892             UncaughtExceptionHandler ueh = uncaughtExceptionHandler;
2893             return (ueh != null) ? ueh : getThreadGroup();
2894         }
2895     }
2896 
2897     /**
2898      * Set the handler invoked when this thread abruptly terminates
2899      * due to an uncaught exception.
2900      * <p>A thread can take full control of how it responds to uncaught
2901      * exceptions by having its uncaught exception handler explicitly set.
2902      * If no such handler is set then the thread's {@code ThreadGroup}
2903      * object acts as its handler.
2904      * @param ueh the object to use as this thread's uncaught exception
2905      * handler. If {@code null} then this thread has no explicit handler.
2906      * @throws  SecurityException  if the current thread is not allowed to
2907      *          modify this thread.
2908      * @see #setDefaultUncaughtExceptionHandler
2909      * @see ThreadGroup#uncaughtException
2910      * @since 1.5
2911      */
2912     public void setUncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
2913         checkAccess();
2914         uncaughtExceptionHandler(ueh);
2915     }
2916 
2917     void uncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
2918         uncaughtExceptionHandler = ueh;
2919     }
2920 
2921     /**
2922      * Dispatch an uncaught exception to the handler. This method is
2923      * called when a thread terminates with an exception.
2924      */
2925     void dispatchUncaughtException(Throwable e) {
2926         getUncaughtExceptionHandler().uncaughtException(this, e);
2927     }
2928 
2929     /**
2930      * Holder class for constants.
2931      */
2932     @SuppressWarnings("removal")
2933     private static class Constants {
2934         // Thread group for virtual threads.
2935         static final ThreadGroup VTHREAD_GROUP;
2936 
2937         // AccessControlContext that doesn't support any permissions.
2938         @SuppressWarnings("removal")
2939         static final AccessControlContext NO_PERMISSIONS_ACC;
2940 
2941         // Placeholder TCCL when thread locals not supported
2942         static final ClassLoader NOT_SUPPORTED_CLASSLOADER;
2943 
2944         static {
2945             var getThreadGroup  = new PrivilegedAction<ThreadGroup>() {
2946                 @Override
2947                 public ThreadGroup run() {
2948                     ThreadGroup parent = Thread.currentCarrierThread().getThreadGroup();
2949                     for (ThreadGroup p; (p = parent.getParent()) != null; )
2950                         parent = p;
2951                     return parent;
2952                 }
2953             };
2954             @SuppressWarnings("removal")
2955             ThreadGroup root = AccessController.doPrivileged(getThreadGroup);
2956             VTHREAD_GROUP = new ThreadGroup(root, "VirtualThreads", MAX_PRIORITY, false);
2957 
2958             NO_PERMISSIONS_ACC = new AccessControlContext(new ProtectionDomain[] {
2959                 new ProtectionDomain(null, null)
2960             });
2961 
2962             var createClassLoader = new PrivilegedAction<ClassLoader>() {
2963                 @Override
2964                 public ClassLoader run() {
2965                     return new ClassLoader(null) { };
2966                 }
2967             };
2968             @SuppressWarnings("removal")
2969             ClassLoader loader = AccessController.doPrivileged(createClassLoader);
2970             NOT_SUPPORTED_CLASSLOADER = loader;
2971         }
2972     }
2973 
2974     /**
2975      * Returns the special ThreadGroup for virtual threads.
2976      */
2977     static ThreadGroup virtualThreadGroup() {
2978         return Constants.VTHREAD_GROUP;
2979     }
2980 
2981     // The following three initially uninitialized fields are exclusively
2982     // managed by class java.util.concurrent.ThreadLocalRandom. These
2983     // fields are used to build the high-performance PRNGs in the
2984     // concurrent code.
2985 
2986     /** The current seed for a ThreadLocalRandom */
2987     long threadLocalRandomSeed;
2988 
2989     /** Probe hash value; nonzero if threadLocalRandomSeed initialized */
2990     int threadLocalRandomProbe;
2991 
2992     /** Secondary seed isolated from public ThreadLocalRandom sequence */
2993     int threadLocalRandomSecondarySeed;
2994 
2995     /** The thread container that this thread is in */
2996     private volatile ThreadContainer container;  // @Stable candidate?
2997     ThreadContainer threadContainer() {
2998         return container;
2999     }
3000     void setThreadContainer(ThreadContainer container) {
3001         // assert this.container == null;
3002         this.container = container;
3003     }
3004 
3005     /** The top of this stack of stackable scopes owned by this thread */
3006     private volatile StackableScope headStackableScopes;
3007     StackableScope headStackableScopes() {
3008         return headStackableScopes;
3009     }
3010     static void setHeadStackableScope(StackableScope scope) {
3011         currentThread().headStackableScopes = scope;
3012     }
3013 
3014     /* Some private helper methods */
3015     private native void setPriority0(int newPriority);
3016     private native void interrupt0();
3017     private static native void clearInterruptEvent();
3018     private native void setNativeName(String name);
3019 
3020     // The address of the next thread identifier, see ThreadIdentifiers.
3021     private static native long getNextThreadIdOffset();
3022 }