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