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