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