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