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