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