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