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