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