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