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