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