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