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