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