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 * This implementation uses a loop of {@code this.wait} calls
1885 * 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 if (!isAlive())
1905 return;
1906
1907 // ensure there is a notifyAll to wake up waiters when this thread terminates
1908 if (this instanceof VirtualThread vthread) {
1909 vthread.beforeJoin();
1910 }
1911
1912 synchronized (this) {
1913 if (millis > 0) {
1914 if (isAlive()) {
1915 final long startTime = System.nanoTime();
1916 long delay = millis;
1917 do {
1918 wait(delay);
1919 } while (isAlive() && (delay = millis -
1920 NANOSECONDS.toMillis(System.nanoTime() - startTime)) > 0);
1921 }
1922 } else {
1923 while (isAlive()) {
1924 wait(0);
1925 }
1926 }
1927 }
1928 }
1929
1930 /**
1931 * Waits at most {@code millis} milliseconds plus
1932 * {@code nanos} nanoseconds for this thread to terminate.
1933 * If both arguments are {@code 0}, it means to wait forever.
1934 * This method returns immediately, without waiting, if the thread has not
1935 * been {@link #start() started}.
1936 *
1937 * @implNote
1938 * This implementation uses a loop of {@code this.wait} calls
1939 * conditioned on {@code this.isAlive}. As a thread terminates the
1940 * {@code this.notifyAll} method is invoked. It is recommended that
1941 * applications not use {@code wait}, {@code notify}, or
1942 * {@code notifyAll} on {@code Thread} instances.
1943 *
1944 * @param millis
1945 * the time to wait in milliseconds
1946 *
1947 * @param nanos
1948 * {@code 0-999999} additional nanoseconds to wait
1949 *
1950 * @throws IllegalArgumentException
1951 * if the value of {@code millis} is negative, or the value
1952 * of {@code nanos} is not in the range {@code 0-999999}
1953 *
1954 * @throws InterruptedException
1955 * if any thread has interrupted the current thread. The
1956 * <i>interrupted status</i> of the current thread is
1957 * cleared when this exception is thrown.
1958 */
1959 public final void join(long millis, int nanos) throws InterruptedException {
1960 if (millis < 0) {
1961 throw new IllegalArgumentException("timeout value is negative");
1962 }
1963
1964 if (nanos < 0 || nanos > 999999) {
1965 throw new IllegalArgumentException("nanosecond timeout value out of range");
1966 }
1967
1968 if (nanos > 0 && millis < Long.MAX_VALUE) {
1969 millis++;
1970 }
1971 join(millis);
1972 }
1973
1974 /**
1975 * Waits for this thread to terminate.
1976 *
1977 * <p> An invocation of this method behaves in exactly the same
1978 * way as the invocation
1979 *
1980 * <blockquote>
1981 * {@linkplain #join(long) join}{@code (0)}
1982 * </blockquote>
1983 *
1984 * @throws InterruptedException
1985 * if any thread has interrupted the current thread. The
1986 * <i>interrupted status</i> of the current thread is
1987 * cleared when this exception is thrown.
1988 */
1989 public final void join() throws InterruptedException {
1990 join(0);
1991 }
1992
1993 /**
1994 * Waits for this thread to terminate for up to the given waiting duration.
1995 *
1996 * <p> This method does not wait if the duration to wait is less than or
1997 * equal to zero. In this case, the method just tests if the thread has
1998 * terminated.
1999 *
2000 * @param duration
2001 * the maximum duration to wait
2002 *
2003 * @return {@code true} if the thread has terminated, {@code false} if the
2004 * thread has not terminated
2005 *
2006 * @throws InterruptedException
2007 * if the current thread is interrupted while waiting.
2008 * The <i>interrupted status</i> of the current thread is cleared
2009 * when this exception is thrown.
2010 *
2011 * @throws IllegalThreadStateException
2012 * if this thread has not been started.
2013 *
2014 * @since 19
2015 */
2016 public final boolean join(Duration duration) throws InterruptedException {
2017 long nanos = NANOSECONDS.convert(duration); // MAX_VALUE if > 292 years
2018
2019 Thread.State state = threadState();
2020 if (state == State.NEW)
2021 throw new IllegalThreadStateException("Thread not started");
2022 if (state == State.TERMINATED)
2023 return true;
2024 if (nanos <= 0)
2025 return false;
2026
2027 // convert to milliseconds
2028 long millis = MILLISECONDS.convert(nanos, NANOSECONDS);
2029 if (nanos > NANOSECONDS.convert(millis, MILLISECONDS)) {
2030 millis += 1L;
2031 }
2032 join(millis);
2033 return isTerminated();
2034 }
2035
2036 /**
2037 * Prints a stack trace of the current thread to the standard error stream.
2038 * This method is useful for debugging.
2039 */
2040 public static void dumpStack() {
2041 new Exception("Stack trace").printStackTrace();
2042 }
2043
2044 /**
2045 * Marks this thread as either a <i>daemon</i> or <i>non-daemon</i> thread.
2046 * The <a href="Runtime.html#shutdown">shutdown sequence</a> begins when all
2047 * started non-daemon threads have terminated.
2048 *
2049 * <p> The daemon status of a virtual thread is always {@code true} and cannot be
2050 * changed by this method to {@code false}.
2051 *
2052 * <p> This method must be invoked before the thread is started. The behavior
2053 * of this method when the thread has terminated is not specified.
2054 *
2055 * @param on
2056 * if {@code true}, marks this thread as a daemon thread
2057 *
2058 * @throws IllegalArgumentException
2059 * if this is a virtual thread and {@code on} is false
2060 * @throws IllegalThreadStateException
2061 * if this thread is {@linkplain #isAlive alive}
2062 */
2063 public final void setDaemon(boolean on) {
2064 if (isVirtual() && !on)
2065 throw new IllegalArgumentException("'false' not legal for virtual threads");
2066 if (isAlive())
2067 throw new IllegalThreadStateException();
2068 if (!isVirtual())
2069 daemon(on);
2070 }
2071
2072 void daemon(boolean on) {
2073 holder.daemon = on;
2074 }
2075
2076 /**
2077 * Tests if this thread is a daemon thread.
2078 * The daemon status of a virtual thread is always {@code true}.
2079 *
2080 * @return {@code true} if this thread is a daemon thread;
2081 * {@code false} otherwise.
2082 * @see #setDaemon(boolean)
2083 */
2084 public final boolean isDaemon() {
2085 if (isVirtual()) {
2086 return true;
2087 } else {
2088 return holder.daemon;
2089 }
2090 }
2091
2092 /**
2093 * Does nothing.
2094 *
2095 * @deprecated This method originally determined if the currently running
2096 * thread had permission to modify this thread. This method was only useful
2097 * in conjunction with {@linkplain SecurityManager the Security Manager},
2098 * which is no longer supported. There is no replacement for the Security
2099 * Manager or this method.
2100 */
2101 @Deprecated(since="17", forRemoval=true)
2102 public final void checkAccess() { }
2103
2104 /**
2105 * Returns a string representation of this thread. The string representation
2106 * will usually include the thread's {@linkplain #threadId() identifier} and
2107 * name. The default implementation for platform threads includes the thread's
2108 * identifier, name, priority, and the name of the thread group.
2109 *
2110 * @return a string representation of this thread.
2111 */
2112 public String toString() {
2113 StringBuilder sb = new StringBuilder("Thread[#");
2114 sb.append(threadId());
2115 sb.append(",");
2116 sb.append(getName());
2117 sb.append(",");
2118 sb.append(getPriority());
2119 sb.append(",");
2120 ThreadGroup group = getThreadGroup();
2121 if (group != null)
2122 sb.append(group.getName());
2123 sb.append("]");
2124 return sb.toString();
2125 }
2126
2127 /**
2128 * Returns the context {@code ClassLoader} for this thread.
2129 * The context {@code ClassLoader} may be set by the creator of the thread
2130 * for use by code running in this thread when loading classes and resources.
2131 * If not {@linkplain #setContextClassLoader set}, the default is to inherit
2132 * the context class loader from the parent thread.
2133 *
2134 * <p> The context {@code ClassLoader} of the primordial thread is typically
2135 * set to the class loader used to load the application.
2136 *
2137 * @return the context {@code ClassLoader} for this thread, or {@code null}
2138 * indicating the system class loader (or, failing that, the
2139 * bootstrap class loader)
2140 *
2141 * @since 1.2
2142 */
2143 public ClassLoader getContextClassLoader() {
2144 return contextClassLoader;
2145 }
2146
2147 /**
2148 * Sets the context {@code ClassLoader} for this thread.
2149 *
2150 * <p> The context {@code ClassLoader} may be set by the creator of the thread
2151 * for use by code running in this thread when loading classes and resources.
2152 *
2153 * @param cl
2154 * the context ClassLoader for this Thread, or null indicating the
2155 * system class loader (or, failing that, the bootstrap class loader)
2156 *
2157 * @since 1.2
2158 */
2159 public void setContextClassLoader(ClassLoader cl) {
2160 contextClassLoader = cl;
2161 }
2162
2163 /**
2164 * Returns {@code true} if and only if the current thread holds the
2165 * monitor lock on the specified object.
2166 *
2167 * <p>This method is designed to allow a program to assert that
2168 * the current thread already holds a specified lock:
2169 * <pre>
2170 * assert Thread.holdsLock(obj);
2171 * </pre>
2172 *
2173 * @param obj the object on which to test lock ownership
2174 * @return {@code true} if the current thread holds the monitor lock on
2175 * the specified object.
2176 * @since 1.4
2177 */
2178 public static native boolean holdsLock(Object obj);
2179
2180 private static final StackTraceElement[] EMPTY_STACK_TRACE
2181 = new StackTraceElement[0];
2182
2183 /**
2184 * Returns an array of stack trace elements representing the stack dump
2185 * of this thread. This method will return a zero-length array if
2186 * this thread has not started, has started but has not yet been
2187 * scheduled to run by the system, or has terminated.
2188 * If the returned array is of non-zero length then the first element of
2189 * the array represents the top of the stack, which is the most recent
2190 * method invocation in the sequence. The last element of the array
2191 * represents the bottom of the stack, which is the least recent method
2192 * invocation in the sequence.
2193 *
2194 * <p>Some virtual machines may, under some circumstances, omit one
2195 * or more stack frames from the stack trace. In the extreme case,
2196 * a virtual machine that has no stack trace information concerning
2197 * this thread is permitted to return a zero-length array from this
2198 * method.
2199 *
2200 * @return an array of {@code StackTraceElement},
2201 * each represents one stack frame.
2202 *
2203 * @see Throwable#getStackTrace
2204 * @since 1.5
2205 */
2206 public StackTraceElement[] getStackTrace() {
2207 if (Thread.currentThread() != this) {
2208 // optimization so we do not call into the vm for threads that
2209 // have not yet started or have terminated
2210 if (!isAlive()) {
2211 return EMPTY_STACK_TRACE;
2212 }
2213 StackTraceElement[] stackTrace = getStackTrace0();
2214 if (stackTrace != null) {
2215 return StackTraceElement.finishInit(stackTrace);
2216 }
2217 return EMPTY_STACK_TRACE;
2218 } else {
2219 return (new Exception()).getStackTrace();
2220 }
2221 }
2222
2223 private native StackTraceElement[] getStackTrace0();
2224
2225 /**
2226 * Returns a map of stack traces for all live platform threads. The map
2227 * does not include virtual threads.
2228 * The map keys are threads and each map value is an array of
2229 * {@code StackTraceElement} that represents the stack dump
2230 * of the corresponding {@code Thread}.
2231 * The returned stack traces are in the format specified for
2232 * the {@link #getStackTrace getStackTrace} method.
2233 *
2234 * <p>The threads may be executing while this method is called.
2235 * The stack trace of each thread only represents a snapshot and
2236 * each stack trace may be obtained at different time. A zero-length
2237 * array will be returned in the map value if the virtual machine has
2238 * no stack trace information about a thread.
2239 *
2240 * @return a {@code Map} from {@code Thread} to an array of
2241 * {@code StackTraceElement} that represents the stack trace of
2242 * the corresponding thread.
2243 *
2244 * @see #getStackTrace
2245 * @see Throwable#getStackTrace
2246 *
2247 * @since 1.5
2248 */
2249 public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
2250 // Get a snapshot of the list of all threads
2251 Thread[] threads = getThreads();
2252 StackTraceElement[][] traces = dumpThreads(threads);
2253 Map<Thread, StackTraceElement[]> m = HashMap.newHashMap(threads.length);
2254 for (int i = 0; i < threads.length; i++) {
2255 StackTraceElement[] stackTrace = traces[i];
2256 if (stackTrace != null) {
2257 m.put(threads[i], stackTrace);
2258 }
2259 // else terminated so we don't put it in the map
2260 }
2261 return m;
2262 }
2263
2264 /**
2265 * Return an array of all live threads.
2266 */
2267 static Thread[] getAllThreads() {
2268 return getThreads();
2269 }
2270
2271 private static native StackTraceElement[][] dumpThreads(Thread[] threads);
2272 private static native Thread[] getThreads();
2273
2274 /**
2275 * Returns the identifier of this Thread. The thread ID is a positive
2276 * {@code long} number generated when this thread was created.
2277 * The thread ID is unique and remains unchanged during its lifetime.
2278 *
2279 * @return this thread's ID
2280 *
2281 * @deprecated This method is not final and may be overridden to return a
2282 * value that is not the thread ID. Use {@link #threadId()} instead.
2283 *
2284 * @since 1.5
2285 */
2286 @Deprecated(since="19")
2287 public long getId() {
2288 return threadId();
2289 }
2290
2291 /**
2292 * Returns the identifier of this Thread. The thread ID is a positive
2293 * {@code long} number generated when this thread was created.
2294 * The thread ID is unique and remains unchanged during its lifetime.
2295 *
2296 * @return this thread's ID
2297 * @since 19
2298 */
2299 public final long threadId() {
2300 return tid;
2301 }
2302
2303 /**
2304 * A thread state. A thread can be in one of the following states:
2305 * <ul>
2306 * <li>{@link #NEW}<br>
2307 * A thread that has not yet started is in this state.
2308 * </li>
2309 * <li>{@link #RUNNABLE}<br>
2310 * A thread executing in the Java virtual machine is in this state.
2311 * </li>
2312 * <li>{@link #BLOCKED}<br>
2313 * A thread that is blocked waiting for a monitor lock
2314 * is in this state.
2315 * </li>
2316 * <li>{@link #WAITING}<br>
2317 * A thread that is waiting indefinitely for another thread to
2318 * perform a particular action is in this state.
2319 * </li>
2320 * <li>{@link #TIMED_WAITING}<br>
2321 * A thread that is waiting for another thread to perform an action
2322 * for up to a specified waiting time is in this state.
2323 * </li>
2324 * <li>{@link #TERMINATED}<br>
2325 * A thread that has exited is in this state.
2326 * </li>
2327 * </ul>
2328 *
2329 * <p>
2330 * A thread can be in only one state at a given point in time.
2331 * These states are virtual machine states which do not reflect
2332 * any operating system thread states.
2333 *
2334 * @since 1.5
2335 * @see #getState
2336 */
2337 public enum State {
2338 /**
2339 * Thread state for a thread which has not yet started.
2340 */
2341 NEW,
2342
2343 /**
2344 * Thread state for a runnable thread. A thread in the runnable
2345 * state is executing in the Java virtual machine but it may
2346 * be waiting for other resources from the operating system
2347 * such as processor.
2348 */
2349 RUNNABLE,
2350
2351 /**
2352 * Thread state for a thread blocked waiting for a monitor lock.
2353 * A thread in the blocked state is waiting for a monitor lock
2354 * to enter a synchronized block/method or
2355 * reenter a synchronized block/method after calling
2356 * {@link Object#wait() Object.wait}.
2357 */
2358 BLOCKED,
2359
2360 /**
2361 * Thread state for a waiting thread.
2362 * A thread is in the waiting state due to calling one of the
2363 * following methods:
2364 * <ul>
2365 * <li>{@link Object#wait() Object.wait} with no timeout</li>
2366 * <li>{@link #join() Thread.join} with no timeout</li>
2367 * <li>{@link LockSupport#park() LockSupport.park}</li>
2368 * </ul>
2369 *
2370 * <p>A thread in the waiting state is waiting for another thread to
2371 * perform a particular action.
2372 *
2373 * For example, a thread that has called {@code Object.wait()}
2374 * on an object is waiting for another thread to call
2375 * {@code Object.notify()} or {@code Object.notifyAll()} on
2376 * that object. A thread that has called {@code Thread.join()}
2377 * is waiting for a specified thread to terminate.
2378 */
2379 WAITING,
2380
2381 /**
2382 * Thread state for a waiting thread with a specified waiting time.
2383 * A thread is in the timed waiting state due to calling one of
2384 * the following methods with a specified positive waiting time:
2385 * <ul>
2386 * <li>{@link #sleep Thread.sleep}</li>
2387 * <li>{@link Object#wait(long) Object.wait} with timeout</li>
2388 * <li>{@link #join(long) Thread.join} with timeout</li>
2389 * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
2390 * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
2391 * </ul>
2392 */
2393 TIMED_WAITING,
2394
2395 /**
2396 * Thread state for a terminated thread.
2397 * The thread has completed execution.
2398 */
2399 TERMINATED;
2400 }
2401
2402 /**
2403 * Returns the state of this thread.
2404 * This method is designed for use in monitoring of the system state,
2405 * not for synchronization control.
2406 *
2407 * @return this thread's state.
2408 * @since 1.5
2409 */
2410 public State getState() {
2411 return threadState();
2412 }
2413
2414 /**
2415 * Returns the state of this thread.
2416 * This method can be used instead of getState as getState is not final and
2417 * so can be overridden to run arbitrary code.
2418 */
2419 State threadState() {
2420 return jdk.internal.misc.VM.toThreadState(holder.threadStatus);
2421 }
2422
2423 /**
2424 * Returns true if the thread has terminated.
2425 */
2426 boolean isTerminated() {
2427 return threadState() == State.TERMINATED;
2428 }
2429
2430 /**
2431 * Interface for handlers invoked when a {@code Thread} abruptly
2432 * terminates due to an uncaught exception.
2433 * <p>When a thread is about to terminate due to an uncaught exception
2434 * the Java Virtual Machine will query the thread for its
2435 * {@code UncaughtExceptionHandler} using
2436 * {@link #getUncaughtExceptionHandler} and will invoke the handler's
2437 * {@code uncaughtException} method, passing the thread and the
2438 * exception as arguments.
2439 * If a thread has not had its {@code UncaughtExceptionHandler}
2440 * explicitly set, then its {@code ThreadGroup} object acts as its
2441 * {@code UncaughtExceptionHandler}. If the {@code ThreadGroup} object
2442 * has no
2443 * special requirements for dealing with the exception, it can forward
2444 * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
2445 * default uncaught exception handler}.
2446 *
2447 * @see #setDefaultUncaughtExceptionHandler
2448 * @see #setUncaughtExceptionHandler
2449 * @see ThreadGroup#uncaughtException
2450 * @since 1.5
2451 */
2452 @FunctionalInterface
2453 public interface UncaughtExceptionHandler {
2454 /**
2455 * Method invoked when the given thread terminates due to the
2456 * given uncaught exception.
2457 * <p>Any exception thrown by this method will be ignored by the
2458 * Java Virtual Machine.
2459 * @param t the thread
2460 * @param e the exception
2461 */
2462 void uncaughtException(Thread t, Throwable e);
2463 }
2464
2465 // null unless explicitly set
2466 private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
2467
2468 // null unless explicitly set
2469 private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
2470
2471 /**
2472 * Set the default handler invoked when a thread abruptly terminates
2473 * due to an uncaught exception, and no other handler has been defined
2474 * for that thread.
2475 *
2476 * <p>Uncaught exception handling is controlled first by the thread, then
2477 * by the thread's {@link ThreadGroup} object and finally by the default
2478 * uncaught exception handler. If the thread does not have an explicit
2479 * uncaught exception handler set, and the thread's thread group
2480 * (including parent thread groups) does not specialize its
2481 * {@code uncaughtException} method, then the default handler's
2482 * {@code uncaughtException} method will be invoked.
2483 * <p>By setting the default uncaught exception handler, an application
2484 * can change the way in which uncaught exceptions are handled (such as
2485 * logging to a specific device, or file) for those threads that would
2486 * already accept whatever "default" behavior the system
2487 * provided.
2488 *
2489 * <p>Note that the default uncaught exception handler should not usually
2490 * defer to the thread's {@code ThreadGroup} object, as that could cause
2491 * infinite recursion.
2492 *
2493 * @param ueh the object to use as the default uncaught exception handler.
2494 * If {@code null} then there is no default handler.
2495 *
2496 * @see #setUncaughtExceptionHandler
2497 * @see #getUncaughtExceptionHandler
2498 * @see ThreadGroup#uncaughtException
2499 * @since 1.5
2500 */
2501 public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
2502 defaultUncaughtExceptionHandler = ueh;
2503 }
2504
2505 /**
2506 * Returns the default handler invoked when a thread abruptly terminates
2507 * due to an uncaught exception. If the returned value is {@code null},
2508 * there is no default.
2509 * @since 1.5
2510 * @see #setDefaultUncaughtExceptionHandler
2511 * @return the default uncaught exception handler for all threads
2512 */
2513 public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
2514 return defaultUncaughtExceptionHandler;
2515 }
2516
2517 /**
2518 * Returns the handler invoked when this thread abruptly terminates
2519 * due to an uncaught exception. If this thread has not had an
2520 * uncaught exception handler explicitly set then this thread's
2521 * {@code ThreadGroup} object is returned, unless this thread
2522 * has terminated, in which case {@code null} is returned.
2523 * @since 1.5
2524 * @return the uncaught exception handler for this thread
2525 */
2526 public UncaughtExceptionHandler getUncaughtExceptionHandler() {
2527 if (isTerminated()) {
2528 // uncaughtExceptionHandler may be set to null after thread terminates
2529 return null;
2530 } else {
2531 UncaughtExceptionHandler ueh = uncaughtExceptionHandler;
2532 return (ueh != null) ? ueh : getThreadGroup();
2533 }
2534 }
2535
2536 /**
2537 * Set the handler invoked when this thread abruptly terminates
2538 * due to an uncaught exception.
2539 * <p>A thread can take full control of how it responds to uncaught
2540 * exceptions by having its uncaught exception handler explicitly set.
2541 * If no such handler is set then the thread's {@code ThreadGroup}
2542 * object acts as its handler.
2543 * @param ueh the object to use as this thread's uncaught exception
2544 * handler. If {@code null} then this thread has no explicit handler.
2545 * @see #setDefaultUncaughtExceptionHandler
2546 * @see ThreadGroup#uncaughtException
2547 * @since 1.5
2548 */
2549 public void setUncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
2550 uncaughtExceptionHandler(ueh);
2551 }
2552
2553 void uncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
2554 uncaughtExceptionHandler = ueh;
2555 }
2556
2557 /**
2558 * Dispatch an uncaught exception to the handler. This method is
2559 * called when a thread terminates with an exception.
2560 */
2561 void dispatchUncaughtException(Throwable e) {
2562 getUncaughtExceptionHandler().uncaughtException(this, e);
2563 }
2564
2565 /**
2566 * Holder class for constants.
2567 */
2568 private static class Constants {
2569 // Thread group for virtual threads.
2570 static final ThreadGroup VTHREAD_GROUP;
2571
2572 static {
2573 ThreadGroup root = Thread.currentCarrierThread().getThreadGroup();
2574 for (ThreadGroup p; (p = root.getParent()) != null; ) {
2575 root = p;
2576 }
2577 VTHREAD_GROUP = new ThreadGroup(root, "VirtualThreads", MAX_PRIORITY, false);
2578 }
2579 }
2580
2581 /**
2582 * Returns the special ThreadGroup for virtual threads.
2583 */
2584 static ThreadGroup virtualThreadGroup() {
2585 return Constants.VTHREAD_GROUP;
2586 }
2587
2588 // The following three initially uninitialized fields are exclusively
2589 // managed by class java.util.concurrent.ThreadLocalRandom. These
2590 // fields are used to build the high-performance PRNGs in the
2591 // concurrent code.
2592
2593 /** The current seed for a ThreadLocalRandom */
2594 long threadLocalRandomSeed;
2595
2596 /** Probe hash value; nonzero if threadLocalRandomSeed initialized */
2597 int threadLocalRandomProbe;
2598
2599 /** Secondary seed isolated from public ThreadLocalRandom sequence */
2600 int threadLocalRandomSecondarySeed;
2601
2602 /** The thread container that this thread is in */
2603 private @Stable ThreadContainer container;
2604 ThreadContainer threadContainer() {
2605 return container;
2606 }
2607 void setThreadContainer(ThreadContainer container) {
2608 // assert this.container == null;
2609 this.container = container;
2610 }
2611
2612 /** The top of this stack of stackable scopes owned by this thread */
2613 private volatile StackableScope headStackableScopes;
2614 StackableScope headStackableScopes() {
2615 return headStackableScopes;
2616 }
2617 static void setHeadStackableScope(StackableScope scope) {
2618 currentThread().headStackableScopes = scope;
2619 }
2620
2621 /* Some private helper methods */
2622 private native void setPriority0(int newPriority);
2623 private native void interrupt0();
2624 private static native void clearInterruptEvent();
2625 private native void setNativeName(String name);
2626
2627 // The address of the next thread identifier, see ThreadIdentifiers.
2628 private static native long getNextThreadIdOffset();
2629 }