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