1 /* 2 * Copyright (c) 1994, 2018, 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.ref.ReferenceQueue; 30 import java.lang.ref.WeakReference; 31 import java.security.AccessController; 32 import java.security.AccessControlContext; 33 import java.security.PrivilegedAction; 34 import java.util.Map; 35 import java.util.HashMap; 36 import java.util.concurrent.ConcurrentHashMap; 37 import java.util.concurrent.ConcurrentMap; 38 import java.util.concurrent.locks.LockSupport; 39 40 import jdk.internal.misc.TerminatingThreadLocal; 41 import sun.nio.ch.Interruptible; 42 import jdk.internal.reflect.CallerSensitive; 43 import jdk.internal.reflect.Reflection; 44 import sun.security.util.SecurityConstants; 45 import jdk.internal.HotSpotIntrinsicCandidate; 46 47 /** 48 * A <i>thread</i> is a thread of execution in a program. The Java 49 * Virtual Machine allows an application to have multiple threads of 50 * execution running concurrently. 51 * <p> 52 * Every thread has a priority. Threads with higher priority are 53 * executed in preference to threads with lower priority. Each thread 54 * may or may not also be marked as a daemon. When code running in 55 * some thread creates a new {@code Thread} object, the new 56 * thread has its priority initially set equal to the priority of the 57 * creating thread, and is a daemon thread if and only if the 58 * creating thread is a daemon. 59 * <p> 60 * When a Java Virtual Machine starts up, there is usually a single 61 * non-daemon thread (which typically calls the method named 62 * {@code main} of some designated class). The Java Virtual 63 * Machine continues to execute threads until either of the following 64 * occurs: 65 * <ul> 66 * <li>The {@code exit} method of class {@code Runtime} has been 67 * called and the security manager has permitted the exit operation 68 * to take place. 69 * <li>All threads that are not daemon threads have died, either by 70 * returning from the call to the {@code run} method or by 71 * throwing an exception that propagates beyond the {@code run} 72 * method. 73 * </ul> 74 * <p> 75 * There are two ways to create a new thread of execution. One is to 76 * declare a class to be a subclass of {@code Thread}. This 77 * subclass should override the {@code run} method of class 78 * {@code Thread}. An instance of the subclass can then be 79 * allocated and started. For example, a thread that computes primes 80 * larger than a stated value could be written as follows: 81 * <hr><blockquote><pre> 82 * class PrimeThread extends Thread { 83 * long minPrime; 84 * PrimeThread(long minPrime) { 85 * this.minPrime = minPrime; 86 * } 87 * 88 * public void run() { 89 * // compute primes larger than minPrime 90 * . . . 91 * } 92 * } 93 * </pre></blockquote><hr> 94 * <p> 95 * The following code would then create a thread and start it running: 96 * <blockquote><pre> 97 * PrimeThread p = new PrimeThread(143); 98 * p.start(); 99 * </pre></blockquote> 100 * <p> 101 * The other way to create a thread is to declare a class that 102 * implements the {@code Runnable} interface. That class then 103 * implements the {@code run} method. An instance of the class can 104 * then be allocated, passed as an argument when creating 105 * {@code Thread}, and started. The same example in this other 106 * style looks like the following: 107 * <hr><blockquote><pre> 108 * class PrimeRun implements Runnable { 109 * long minPrime; 110 * PrimeRun(long minPrime) { 111 * this.minPrime = minPrime; 112 * } 113 * 114 * public void run() { 115 * // compute primes larger than minPrime 116 * . . . 117 * } 118 * } 119 * </pre></blockquote><hr> 120 * <p> 121 * The following code would then create a thread and start it running: 122 * <blockquote><pre> 123 * PrimeRun p = new PrimeRun(143); 124 * new Thread(p).start(); 125 * </pre></blockquote> 126 * <p> 127 * Every thread has a name for identification purposes. More than 128 * one thread may have the same name. If a name is not specified when 129 * a thread is created, a new name is generated for it. 130 * <p> 131 * Unless otherwise noted, passing a {@code null} argument to a constructor 132 * or method in this class will cause a {@link NullPointerException} to be 133 * thrown. 134 * 135 * @author unascribed 136 * @see Runnable 137 * @see Runtime#exit(int) 138 * @see #run() 139 * @see #stop() 140 * @since 1.0 141 */ 142 public 143 class Thread implements Runnable { 144 /* Make sure registerNatives is the first thing <clinit> does. */ 145 private static native void registerNatives(); 146 static { 147 registerNatives(); 148 } 149 150 private volatile String name; 151 private int priority; 152 153 /* Whether or not the thread is a daemon thread. */ 154 private boolean daemon = false; 155 156 /* Fields reserved for exclusive use by the JVM */ 157 private boolean stillborn = false; 158 private long eetop; 159 160 /* What will be run. */ 161 private Runnable target; 162 163 /* The group of this thread */ 164 private ThreadGroup group; 165 166 /* The context ClassLoader for this thread */ 167 private ClassLoader contextClassLoader; 168 169 /* The inherited AccessControlContext of this thread */ 170 private AccessControlContext inheritedAccessControlContext; 171 172 /* For autonumbering anonymous threads. */ 173 private static int threadInitNumber; 174 private static synchronized int nextThreadNum() { 175 return threadInitNumber++; 176 } 177 178 /* ThreadLocal values pertaining to this thread. This map is maintained 179 * by the ThreadLocal class. */ 180 ThreadLocal.ThreadLocalMap threadLocals = null; 181 182 /* 183 * InheritableThreadLocal values pertaining to this thread. This map is 184 * maintained by the InheritableThreadLocal class. 185 */ 186 ThreadLocal.ThreadLocalMap inheritableThreadLocals = null; 187 188 /* 189 * The requested stack size for this thread, or 0 if the creator did 190 * not specify a stack size. It is up to the VM to do whatever it 191 * likes with this number; some VMs will ignore it. 192 */ 193 private final long stackSize; 194 195 /* 196 * JVM-private state that persists after native thread termination. 197 */ 198 private long nativeParkEventPointer; 199 200 /* 201 * Thread ID 202 */ 203 private final long tid; 204 205 /* For generating thread ID */ 206 private static long threadSeqNumber; 207 208 private static synchronized long nextThreadID() { 209 return ++threadSeqNumber; 210 } 211 212 /* 213 * Java thread status for tools, default indicates thread 'not yet started' 214 */ 215 private volatile int threadStatus; 216 217 /** 218 * The argument supplied to the current call to 219 * java.util.concurrent.locks.LockSupport.park. 220 * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker 221 * Accessed using java.util.concurrent.locks.LockSupport.getBlocker 222 */ 223 volatile Object parkBlocker; 224 225 /* The object in which this thread is blocked in an interruptible I/O 226 * operation, if any. The blocker's interrupt method should be invoked 227 * after setting this thread's interrupt status. 228 */ 229 private volatile Interruptible blocker; 230 private final Object blockerLock = new Object(); 231 232 /* Set the blocker field; invoked via jdk.internal.misc.SharedSecrets 233 * from java.nio code 234 */ 235 static void blockedOn(Interruptible b) { 236 Thread me = Thread.currentThread(); 237 synchronized (me.blockerLock) { 238 me.blocker = b; 239 } 240 } 241 242 /** 243 * The minimum priority that a thread can have. 244 */ 245 public static final int MIN_PRIORITY = 1; 246 247 /** 248 * The default priority that is assigned to a thread. 249 */ 250 public static final int NORM_PRIORITY = 5; 251 252 /** 253 * The maximum priority that a thread can have. 254 */ 255 public static final int MAX_PRIORITY = 10; 256 257 /** 258 * Returns a reference to the currently executing thread object. 259 * 260 * @return the currently executing thread. 261 */ 262 @HotSpotIntrinsicCandidate 263 public static native Thread currentThread(); 264 265 /** 266 * A hint to the scheduler that the current thread is willing to yield 267 * its current use of a processor. The scheduler is free to ignore this 268 * hint. 269 * 270 * <p> Yield is a heuristic attempt to improve relative progression 271 * between threads that would otherwise over-utilise a CPU. Its use 272 * should be combined with detailed profiling and benchmarking to 273 * ensure that it actually has the desired effect. 274 * 275 * <p> It is rarely appropriate to use this method. It may be useful 276 * for debugging or testing purposes, where it may help to reproduce 277 * bugs due to race conditions. It may also be useful when designing 278 * concurrency control constructs such as the ones in the 279 * {@link java.util.concurrent.locks} package. 280 */ 281 public static native void yield(); 282 283 /** 284 * Causes the currently executing thread to sleep (temporarily cease 285 * execution) for the specified number of milliseconds, subject to 286 * the precision and accuracy of system timers and schedulers. The thread 287 * does not lose ownership of any monitors. 288 * 289 * @param millis 290 * the length of time to sleep in milliseconds 291 * 292 * @throws IllegalArgumentException 293 * if the value of {@code millis} is negative 294 * 295 * @throws InterruptedException 296 * if any thread has interrupted the current thread. The 297 * <i>interrupted status</i> of the current thread is 298 * cleared when this exception is thrown. 299 */ 300 public static native void sleep(long millis) throws InterruptedException; 301 302 /** 303 * Causes the currently executing thread to sleep (temporarily cease 304 * execution) for the specified number of milliseconds plus the specified 305 * number of nanoseconds, subject to the precision and accuracy of system 306 * timers and schedulers. The thread does not lose ownership of any 307 * monitors. 308 * 309 * @param millis 310 * the length of time to sleep in milliseconds 311 * 312 * @param nanos 313 * {@code 0-999999} additional nanoseconds to sleep 314 * 315 * @throws IllegalArgumentException 316 * if the value of {@code millis} is negative, or the value of 317 * {@code nanos} is not in the range {@code 0-999999} 318 * 319 * @throws InterruptedException 320 * if any thread has interrupted the current thread. The 321 * <i>interrupted status</i> of the current thread is 322 * cleared when this exception is thrown. 323 */ 324 public static void sleep(long millis, int nanos) 325 throws InterruptedException { 326 if (millis < 0) { 327 throw new IllegalArgumentException("timeout value is negative"); 328 } 329 330 if (nanos < 0 || nanos > 999999) { 331 throw new IllegalArgumentException( 332 "nanosecond timeout value out of range"); 333 } 334 335 if (nanos >= 500000 || (nanos != 0 && millis == 0)) { 336 millis++; 337 } 338 339 sleep(millis); 340 } 341 342 /** 343 * Indicates that the caller is momentarily unable to progress, until the 344 * occurrence of one or more actions on the part of other activities. By 345 * invoking this method within each iteration of a spin-wait loop construct, 346 * the calling thread indicates to the runtime that it is busy-waiting. 347 * The runtime may take action to improve the performance of invoking 348 * spin-wait loop constructions. 349 * 350 * @apiNote 351 * As an example consider a method in a class that spins in a loop until 352 * some flag is set outside of that method. A call to the {@code onSpinWait} 353 * method should be placed inside the spin loop. 354 * <pre>{@code 355 * class EventHandler { 356 * volatile boolean eventNotificationNotReceived; 357 * void waitForEventAndHandleIt() { 358 * while ( eventNotificationNotReceived ) { 359 * java.lang.Thread.onSpinWait(); 360 * } 361 * readAndProcessEvent(); 362 * } 363 * 364 * void readAndProcessEvent() { 365 * // Read event from some source and process it 366 * . . . 367 * } 368 * } 369 * }</pre> 370 * <p> 371 * The code above would remain correct even if the {@code onSpinWait} 372 * method was not called at all. However on some architectures the Java 373 * Virtual Machine may issue the processor instructions to address such 374 * code patterns in a more beneficial way. 375 * 376 * @since 9 377 */ 378 @HotSpotIntrinsicCandidate 379 public static void onSpinWait() {} 380 381 /** 382 * Initializes a Thread. 383 * 384 * @param g the Thread group 385 * @param target the object whose run() method gets called 386 * @param name the name of the new Thread 387 * @param stackSize the desired stack size for the new thread, or 388 * zero to indicate that this parameter is to be ignored. 389 * @param acc the AccessControlContext to inherit, or 390 * AccessController.getContext() if null 391 * @param inheritThreadLocals if {@code true}, inherit initial values for 392 * inheritable thread-locals from the constructing thread 393 */ 394 private Thread(ThreadGroup g, Runnable target, String name, 395 long stackSize, AccessControlContext acc, 396 boolean inheritThreadLocals) { 397 if (name == null) { 398 throw new NullPointerException("name cannot be null"); 399 } 400 401 this.name = name; 402 403 Thread parent = currentThread(); 404 SecurityManager security = System.getSecurityManager(); 405 if (g == null) { 406 /* Determine if it's an applet or not */ 407 408 /* If there is a security manager, ask the security manager 409 what to do. */ 410 if (security != null) { 411 g = security.getThreadGroup(); 412 } 413 414 /* If the security manager doesn't have a strong opinion 415 on the matter, use the parent thread group. */ 416 if (g == null) { 417 g = parent.getThreadGroup(); 418 } 419 } 420 421 /* checkAccess regardless of whether or not threadgroup is 422 explicitly passed in. */ 423 g.checkAccess(); 424 425 /* 426 * Do we have the required permissions? 427 */ 428 if (security != null) { 429 if (isCCLOverridden(getClass())) { 430 security.checkPermission( 431 SecurityConstants.SUBCLASS_IMPLEMENTATION_PERMISSION); 432 } 433 } 434 435 g.addUnstarted(); 436 437 this.group = g; 438 this.daemon = parent.isDaemon(); 439 this.priority = parent.getPriority(); 440 if (security == null || isCCLOverridden(parent.getClass())) 441 this.contextClassLoader = parent.getContextClassLoader(); 442 else 443 this.contextClassLoader = parent.contextClassLoader; 444 this.inheritedAccessControlContext = 445 acc != null ? acc : AccessController.getContext(); 446 this.target = target; 447 setPriority(priority); 448 if (inheritThreadLocals && parent.inheritableThreadLocals != null) 449 this.inheritableThreadLocals = 450 ThreadLocal.createInheritedMap(parent.inheritableThreadLocals); 451 /* Stash the specified stack size in case the VM cares */ 452 this.stackSize = stackSize; 453 454 /* Set thread ID */ 455 this.tid = nextThreadID(); 456 } 457 458 /** 459 * Throws CloneNotSupportedException as a Thread can not be meaningfully 460 * cloned. Construct a new Thread instead. 461 * 462 * @throws CloneNotSupportedException 463 * always 464 */ 465 @Override 466 protected Object clone() throws CloneNotSupportedException { 467 throw new CloneNotSupportedException(); 468 } 469 470 /** 471 * Allocates a new {@code Thread} object. This constructor has the same 472 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} 473 * {@code (null, null, gname)}, where {@code gname} is a newly generated 474 * name. Automatically generated names are of the form 475 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer. 476 */ 477 public Thread() { 478 this(null, null, "Thread-" + nextThreadNum(), 0); 479 } 480 481 /** 482 * Allocates a new {@code Thread} object. This constructor has the same 483 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} 484 * {@code (null, target, gname)}, where {@code gname} is a newly generated 485 * name. Automatically generated names are of the form 486 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer. 487 * 488 * @param target 489 * the object whose {@code run} method is invoked when this thread 490 * is started. If {@code null}, this classes {@code run} method does 491 * nothing. 492 */ 493 public Thread(Runnable target) { 494 this(null, target, "Thread-" + nextThreadNum(), 0); 495 } 496 497 /** 498 * Creates a new Thread that inherits the given AccessControlContext 499 * but thread-local variables are not inherited. 500 * This is not a public constructor. 501 */ 502 Thread(Runnable target, AccessControlContext acc) { 503 this(null, target, "Thread-" + nextThreadNum(), 0, acc, false); 504 } 505 506 /** 507 * Allocates a new {@code Thread} object. This constructor has the same 508 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} 509 * {@code (group, target, gname)} ,where {@code gname} is a newly generated 510 * name. Automatically generated names are of the form 511 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer. 512 * 513 * @param group 514 * the thread group. If {@code null} and there is a security 515 * manager, the group is determined by {@linkplain 516 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}. 517 * If there is not a security manager or {@code 518 * SecurityManager.getThreadGroup()} returns {@code null}, the group 519 * is set to the current thread's thread group. 520 * 521 * @param target 522 * the object whose {@code run} method is invoked when this thread 523 * is started. If {@code null}, this thread's run method is invoked. 524 * 525 * @throws SecurityException 526 * if the current thread cannot create a thread in the specified 527 * thread group 528 */ 529 public Thread(ThreadGroup group, Runnable target) { 530 this(group, target, "Thread-" + nextThreadNum(), 0); 531 } 532 533 /** 534 * Allocates a new {@code Thread} object. This constructor has the same 535 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} 536 * {@code (null, null, name)}. 537 * 538 * @param name 539 * the name of the new thread 540 */ 541 public Thread(String name) { 542 this(null, null, name, 0); 543 } 544 545 /** 546 * Allocates a new {@code Thread} object. This constructor has the same 547 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} 548 * {@code (group, null, name)}. 549 * 550 * @param group 551 * the thread group. If {@code null} and there is a security 552 * manager, the group is determined by {@linkplain 553 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}. 554 * If there is not a security manager or {@code 555 * SecurityManager.getThreadGroup()} returns {@code null}, the group 556 * is set to the current thread's thread group. 557 * 558 * @param name 559 * the name of the new thread 560 * 561 * @throws SecurityException 562 * if the current thread cannot create a thread in the specified 563 * thread group 564 */ 565 public Thread(ThreadGroup group, String name) { 566 this(group, null, name, 0); 567 } 568 569 /** 570 * Allocates a new {@code Thread} object. This constructor has the same 571 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} 572 * {@code (null, target, name)}. 573 * 574 * @param target 575 * the object whose {@code run} method is invoked when this thread 576 * is started. If {@code null}, this thread's run method is invoked. 577 * 578 * @param name 579 * the name of the new thread 580 */ 581 public Thread(Runnable target, String name) { 582 this(null, target, name, 0); 583 } 584 585 /** 586 * Allocates a new {@code Thread} object so that it has {@code target} 587 * as its run object, has the specified {@code name} as its name, 588 * and belongs to the thread group referred to by {@code group}. 589 * 590 * <p>If there is a security manager, its 591 * {@link SecurityManager#checkAccess(ThreadGroup) checkAccess} 592 * method is invoked with the ThreadGroup as its argument. 593 * 594 * <p>In addition, its {@code checkPermission} method is invoked with 595 * the {@code RuntimePermission("enableContextClassLoaderOverride")} 596 * permission when invoked directly or indirectly by the constructor 597 * of a subclass which overrides the {@code getContextClassLoader} 598 * or {@code setContextClassLoader} methods. 599 * 600 * <p>The priority of the newly created thread is set equal to the 601 * priority of the thread creating it, that is, the currently running 602 * thread. The method {@linkplain #setPriority setPriority} may be 603 * used to change the priority to a new value. 604 * 605 * <p>The newly created thread is initially marked as being a daemon 606 * thread if and only if the thread creating it is currently marked 607 * as a daemon thread. The method {@linkplain #setDaemon setDaemon} 608 * may be used to change whether or not a thread is a daemon. 609 * 610 * @param group 611 * the thread group. If {@code null} and there is a security 612 * manager, the group is determined by {@linkplain 613 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}. 614 * If there is not a security manager or {@code 615 * SecurityManager.getThreadGroup()} returns {@code null}, the group 616 * is set to the current thread's thread group. 617 * 618 * @param target 619 * the object whose {@code run} method is invoked when this thread 620 * is started. If {@code null}, this thread's run method is invoked. 621 * 622 * @param name 623 * the name of the new thread 624 * 625 * @throws SecurityException 626 * if the current thread cannot create a thread in the specified 627 * thread group or cannot override the context class loader methods. 628 */ 629 public Thread(ThreadGroup group, Runnable target, String name) { 630 this(group, target, name, 0); 631 } 632 633 /** 634 * Allocates a new {@code Thread} object so that it has {@code target} 635 * as its run object, has the specified {@code name} as its name, 636 * and belongs to the thread group referred to by {@code group}, and has 637 * the specified <i>stack size</i>. 638 * 639 * <p>This constructor is identical to {@link 640 * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact 641 * that it allows the thread stack size to be specified. The stack size 642 * is the approximate number of bytes of address space that the virtual 643 * machine is to allocate for this thread's stack. <b>The effect of the 644 * {@code stackSize} parameter, if any, is highly platform dependent.</b> 645 * 646 * <p>On some platforms, specifying a higher value for the 647 * {@code stackSize} parameter may allow a thread to achieve greater 648 * recursion depth before throwing a {@link StackOverflowError}. 649 * Similarly, specifying a lower value may allow a greater number of 650 * threads to exist concurrently without throwing an {@link 651 * OutOfMemoryError} (or other internal error). The details of 652 * the relationship between the value of the {@code stackSize} parameter 653 * and the maximum recursion depth and concurrency level are 654 * platform-dependent. <b>On some platforms, the value of the 655 * {@code stackSize} parameter may have no effect whatsoever.</b> 656 * 657 * <p>The virtual machine is free to treat the {@code stackSize} 658 * parameter as a suggestion. If the specified value is unreasonably low 659 * for the platform, the virtual machine may instead use some 660 * platform-specific minimum value; if the specified value is unreasonably 661 * high, the virtual machine may instead use some platform-specific 662 * maximum. Likewise, the virtual machine is free to round the specified 663 * value up or down as it sees fit (or to ignore it completely). 664 * 665 * <p>Specifying a value of zero for the {@code stackSize} parameter will 666 * cause this constructor to behave exactly like the 667 * {@code Thread(ThreadGroup, Runnable, String)} constructor. 668 * 669 * <p><i>Due to the platform-dependent nature of the behavior of this 670 * constructor, extreme care should be exercised in its use. 671 * The thread stack size necessary to perform a given computation will 672 * likely vary from one JRE implementation to another. In light of this 673 * variation, careful tuning of the stack size parameter may be required, 674 * and the tuning may need to be repeated for each JRE implementation on 675 * which an application is to run.</i> 676 * 677 * <p>Implementation note: Java platform implementers are encouraged to 678 * document their implementation's behavior with respect to the 679 * {@code stackSize} parameter. 680 * 681 * 682 * @param group 683 * the thread group. If {@code null} and there is a security 684 * manager, the group is determined by {@linkplain 685 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}. 686 * If there is not a security manager or {@code 687 * SecurityManager.getThreadGroup()} returns {@code null}, the group 688 * is set to the current thread's thread group. 689 * 690 * @param target 691 * the object whose {@code run} method is invoked when this thread 692 * is started. If {@code null}, this thread's run method is invoked. 693 * 694 * @param name 695 * the name of the new thread 696 * 697 * @param stackSize 698 * the desired stack size for the new thread, or zero to indicate 699 * that this parameter is to be ignored. 700 * 701 * @throws SecurityException 702 * if the current thread cannot create a thread in the specified 703 * thread group 704 * 705 * @since 1.4 706 */ 707 public Thread(ThreadGroup group, Runnable target, String name, 708 long stackSize) { 709 this(group, target, name, stackSize, null, true); 710 } 711 712 /** 713 * Allocates a new {@code Thread} object so that it has {@code target} 714 * as its run object, has the specified {@code name} as its name, 715 * belongs to the thread group referred to by {@code group}, has 716 * the specified {@code stackSize}, and inherits initial values for 717 * {@linkplain InheritableThreadLocal inheritable thread-local} variables 718 * if {@code inheritThreadLocals} is {@code true}. 719 * 720 * <p> This constructor is identical to {@link 721 * #Thread(ThreadGroup,Runnable,String,long)} with the added ability to 722 * suppress, or not, the inheriting of initial values for inheritable 723 * thread-local variables from the constructing thread. This allows for 724 * finer grain control over inheritable thread-locals. Care must be taken 725 * when passing a value of {@code false} for {@code inheritThreadLocals}, 726 * as it may lead to unexpected behavior if the new thread executes code 727 * that expects a specific thread-local value to be inherited. 728 * 729 * <p> Specifying a value of {@code true} for the {@code inheritThreadLocals} 730 * parameter will cause this constructor to behave exactly like the 731 * {@code Thread(ThreadGroup, Runnable, String, long)} constructor. 732 * 733 * @param group 734 * the thread group. If {@code null} and there is a security 735 * manager, the group is determined by {@linkplain 736 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}. 737 * If there is not a security manager or {@code 738 * SecurityManager.getThreadGroup()} returns {@code null}, the group 739 * is set to the current thread's thread group. 740 * 741 * @param target 742 * the object whose {@code run} method is invoked when this thread 743 * is started. If {@code null}, this thread's run method is invoked. 744 * 745 * @param name 746 * the name of the new thread 747 * 748 * @param stackSize 749 * the desired stack size for the new thread, or zero to indicate 750 * that this parameter is to be ignored 751 * 752 * @param inheritThreadLocals 753 * if {@code true}, inherit initial values for inheritable 754 * thread-locals from the constructing thread, otherwise no initial 755 * values are inherited 756 * 757 * @throws SecurityException 758 * if the current thread cannot create a thread in the specified 759 * thread group 760 * 761 * @since 9 762 */ 763 public Thread(ThreadGroup group, Runnable target, String name, 764 long stackSize, boolean inheritThreadLocals) { 765 this(group, target, name, stackSize, null, inheritThreadLocals); 766 } 767 768 /** 769 * Causes this thread to begin execution; the Java Virtual Machine 770 * calls the {@code run} method of this thread. 771 * <p> 772 * The result is that two threads are running concurrently: the 773 * current thread (which returns from the call to the 774 * {@code start} method) and the other thread (which executes its 775 * {@code run} method). 776 * <p> 777 * It is never legal to start a thread more than once. 778 * In particular, a thread may not be restarted once it has completed 779 * execution. 780 * 781 * @throws IllegalThreadStateException if the thread was already started. 782 * @see #run() 783 * @see #stop() 784 */ 785 public synchronized void start() { 786 /** 787 * This method is not invoked for the main method thread or "system" 788 * group threads created/set up by the VM. Any new functionality added 789 * to this method in the future may have to also be added to the VM. 790 * 791 * A zero status value corresponds to state "NEW". 792 */ 793 if (threadStatus != 0) 794 throw new IllegalThreadStateException(); 795 796 /* Notify the group that this thread is about to be started 797 * so that it can be added to the group's list of threads 798 * and the group's unstarted count can be decremented. */ 799 group.add(this); 800 801 boolean started = false; 802 try { 803 start0(); 804 started = true; 805 } finally { 806 try { 807 if (!started) { 808 group.threadStartFailed(this); 809 } 810 } catch (Throwable ignore) { 811 /* do nothing. If start0 threw a Throwable then 812 it will be passed up the call stack */ 813 } 814 } 815 } 816 817 private native void start0(); 818 819 /** 820 * If this thread was constructed using a separate 821 * {@code Runnable} run object, then that 822 * {@code Runnable} object's {@code run} method is called; 823 * otherwise, this method does nothing and returns. 824 * <p> 825 * Subclasses of {@code Thread} should override this method. 826 * 827 * @see #start() 828 * @see #stop() 829 * @see #Thread(ThreadGroup, Runnable, String) 830 */ 831 @Override 832 public void run() { 833 if (target != null) { 834 target.run(); 835 } 836 } 837 838 /** 839 * This method is called by the system to give a Thread 840 * a chance to clean up before it actually exits. 841 */ 842 private void exit() { 843 if (TerminatingThreadLocal.REGISTRY.isPresent()) { 844 TerminatingThreadLocal.threadTerminated(); 845 } 846 if (group != null) { 847 group.threadTerminated(this); 848 group = null; 849 } 850 /* Aggressively null out all reference fields: see bug 4006245 */ 851 target = null; 852 /* Speed the release of some of these resources */ 853 threadLocals = null; 854 inheritableThreadLocals = null; 855 inheritedAccessControlContext = null; 856 blocker = null; 857 uncaughtExceptionHandler = null; 858 } 859 860 /** 861 * Forces the thread to stop executing. 862 * <p> 863 * If there is a security manager installed, its {@code checkAccess} 864 * method is called with {@code this} 865 * as its argument. This may result in a 866 * {@code SecurityException} being raised (in the current thread). 867 * <p> 868 * If this thread is different from the current thread (that is, the current 869 * thread is trying to stop a thread other than itself), the 870 * security manager's {@code checkPermission} method (with a 871 * {@code RuntimePermission("stopThread")} argument) is called in 872 * addition. 873 * Again, this may result in throwing a 874 * {@code SecurityException} (in the current thread). 875 * <p> 876 * The thread represented by this thread is forced to stop whatever 877 * it is doing abnormally and to throw a newly created 878 * {@code ThreadDeath} object as an exception. 879 * <p> 880 * It is permitted to stop a thread that has not yet been started. 881 * If the thread is eventually started, it immediately terminates. 882 * <p> 883 * An application should not normally try to catch 884 * {@code ThreadDeath} unless it must do some extraordinary 885 * cleanup operation (note that the throwing of 886 * {@code ThreadDeath} causes {@code finally} clauses of 887 * {@code try} statements to be executed before the thread 888 * officially dies). If a {@code catch} clause catches a 889 * {@code ThreadDeath} object, it is important to rethrow the 890 * object so that the thread actually dies. 891 * <p> 892 * The top-level error handler that reacts to otherwise uncaught 893 * exceptions does not print out a message or otherwise notify the 894 * application if the uncaught exception is an instance of 895 * {@code ThreadDeath}. 896 * 897 * @throws SecurityException if the current thread cannot 898 * modify this thread. 899 * @see #interrupt() 900 * @see #checkAccess() 901 * @see #run() 902 * @see #start() 903 * @see ThreadDeath 904 * @see ThreadGroup#uncaughtException(Thread,Throwable) 905 * @see SecurityManager#checkAccess(Thread) 906 * @see SecurityManager#checkPermission 907 * @deprecated This method is inherently unsafe. Stopping a thread with 908 * Thread.stop causes it to unlock all of the monitors that it 909 * has locked (as a natural consequence of the unchecked 910 * {@code ThreadDeath} exception propagating up the stack). If 911 * any of the objects previously protected by these monitors were in 912 * an inconsistent state, the damaged objects become visible to 913 * other threads, potentially resulting in arbitrary behavior. Many 914 * uses of {@code stop} should be replaced by code that simply 915 * modifies some variable to indicate that the target thread should 916 * stop running. The target thread should check this variable 917 * regularly, and return from its run method in an orderly fashion 918 * if the variable indicates that it is to stop running. If the 919 * target thread waits for long periods (on a condition variable, 920 * for example), the {@code interrupt} method should be used to 921 * interrupt the wait. 922 * For more information, see 923 * <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why 924 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>. 925 */ 926 @Deprecated(since="1.2") 927 public final void stop() { 928 SecurityManager security = System.getSecurityManager(); 929 if (security != null) { 930 checkAccess(); 931 if (this != Thread.currentThread()) { 932 security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION); 933 } 934 } 935 // A zero status value corresponds to "NEW", it can't change to 936 // not-NEW because we hold the lock. 937 if (threadStatus != 0) { 938 resume(); // Wake up thread if it was suspended; no-op otherwise 939 } 940 941 // The VM can handle all thread states 942 stop0(new ThreadDeath()); 943 } 944 945 /** 946 * Throws {@code UnsupportedOperationException}. 947 * 948 * @param obj ignored 949 * 950 * @deprecated This method was originally designed to force a thread to stop 951 * and throw a given {@code Throwable} as an exception. It was 952 * inherently unsafe (see {@link #stop()} for details), and furthermore 953 * could be used to generate exceptions that the target thread was 954 * not prepared to handle. 955 * For more information, see 956 * <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why 957 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>. 958 * This method is subject to removal in a future version of Java SE. 959 */ 960 @Deprecated(since="1.2", forRemoval=true) 961 public final synchronized void stop(Throwable obj) { 962 throw new UnsupportedOperationException(); 963 } 964 965 /** 966 * Interrupts this thread. 967 * 968 * <p> Unless the current thread is interrupting itself, which is 969 * always permitted, the {@link #checkAccess() checkAccess} method 970 * of this thread is invoked, which may cause a {@link 971 * SecurityException} to be thrown. 972 * 973 * <p> If this thread is blocked in an invocation of the {@link 974 * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link 975 * Object#wait(long, int) wait(long, int)} methods of the {@link Object} 976 * class, or of the {@link #join()}, {@link #join(long)}, {@link 977 * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)}, 978 * methods of this class, then its interrupt status will be cleared and it 979 * will receive an {@link InterruptedException}. 980 * 981 * <p> If this thread is blocked in an I/O operation upon an {@link 982 * java.nio.channels.InterruptibleChannel InterruptibleChannel} 983 * then the channel will be closed, the thread's interrupt 984 * status will be set, and the thread will receive a {@link 985 * java.nio.channels.ClosedByInterruptException}. 986 * 987 * <p> If this thread is blocked in a {@link java.nio.channels.Selector} 988 * then the thread's interrupt status will be set and it will return 989 * immediately from the selection operation, possibly with a non-zero 990 * value, just as if the selector's {@link 991 * java.nio.channels.Selector#wakeup wakeup} method were invoked. 992 * 993 * <p> If none of the previous conditions hold then this thread's interrupt 994 * status will be set. </p> 995 * 996 * <p> Interrupting a thread that is not alive need not have any effect. 997 * 998 * @throws SecurityException 999 * if the current thread cannot modify this thread 1000 * 1001 * @revised 6.0 1002 * @spec JSR-51 1003 */ 1004 public void interrupt() { 1005 if (this != Thread.currentThread()) { 1006 checkAccess(); 1007 1008 // thread may be blocked in an I/O operation 1009 synchronized (blockerLock) { 1010 Interruptible b = blocker; 1011 if (b != null) { 1012 interrupt0(); // set interrupt status 1013 b.interrupt(this); 1014 return; 1015 } 1016 } 1017 } 1018 1019 // set interrupt status 1020 interrupt0(); 1021 } 1022 1023 /** 1024 * Tests whether the current thread has been interrupted. The 1025 * <i>interrupted status</i> of the thread is cleared by this method. In 1026 * other words, if this method were to be called twice in succession, the 1027 * second call would return false (unless the current thread were 1028 * interrupted again, after the first call had cleared its interrupted 1029 * status and before the second call had examined it). 1030 * 1031 * <p>A thread interruption ignored because a thread was not alive 1032 * at the time of the interrupt will be reflected by this method 1033 * returning false. 1034 * 1035 * @return {@code true} if the current thread has been interrupted; 1036 * {@code false} otherwise. 1037 * @see #isInterrupted() 1038 * @revised 6.0 1039 */ 1040 public static boolean interrupted() { 1041 return currentThread().isInterrupted(true); 1042 } 1043 1044 /** 1045 * Tests whether this thread has been interrupted. The <i>interrupted 1046 * status</i> of the thread is unaffected by this method. 1047 * 1048 * <p>A thread interruption ignored because a thread was not alive 1049 * at the time of the interrupt will be reflected by this method 1050 * returning false. 1051 * 1052 * @return {@code true} if this thread has been interrupted; 1053 * {@code false} otherwise. 1054 * @see #interrupted() 1055 * @revised 6.0 1056 */ 1057 public boolean isInterrupted() { 1058 return isInterrupted(false); 1059 } 1060 1061 /** 1062 * Tests if some Thread has been interrupted. The interrupted state 1063 * is reset or not based on the value of ClearInterrupted that is 1064 * passed. 1065 */ 1066 @HotSpotIntrinsicCandidate 1067 private native boolean isInterrupted(boolean ClearInterrupted); 1068 1069 /** 1070 * Throws {@link NoSuchMethodError}. 1071 * 1072 * @deprecated This method was originally designed to destroy this 1073 * thread without any cleanup. Any monitors it held would have 1074 * remained locked. However, the method was never implemented. 1075 * If it were to be implemented, it would be deadlock-prone in 1076 * much the manner of {@link #suspend}. If the target thread held 1077 * a lock protecting a critical system resource when it was 1078 * destroyed, no thread could ever access this resource again. 1079 * If another thread ever attempted to lock this resource, deadlock 1080 * would result. Such deadlocks typically manifest themselves as 1081 * "frozen" processes. For more information, see 1082 * <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html"> 1083 * Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>. 1084 * This method is subject to removal in a future version of Java SE. 1085 * @throws NoSuchMethodError always 1086 */ 1087 @Deprecated(since="1.5", forRemoval=true) 1088 public void destroy() { 1089 throw new NoSuchMethodError(); 1090 } 1091 1092 /** 1093 * Tests if this thread is alive. A thread is alive if it has 1094 * been started and has not yet died. 1095 * 1096 * @return {@code true} if this thread is alive; 1097 * {@code false} otherwise. 1098 */ 1099 public final native boolean isAlive(); 1100 1101 /** 1102 * Suspends this thread. 1103 * <p> 1104 * First, the {@code checkAccess} method of this thread is called 1105 * with no arguments. This may result in throwing a 1106 * {@code SecurityException }(in the current thread). 1107 * <p> 1108 * If the thread is alive, it is suspended and makes no further 1109 * progress unless and until it is resumed. 1110 * 1111 * @throws SecurityException if the current thread cannot modify 1112 * this thread. 1113 * @see #checkAccess 1114 * @deprecated This method has been deprecated, as it is 1115 * inherently deadlock-prone. If the target thread holds a lock on the 1116 * monitor protecting a critical system resource when it is suspended, no 1117 * thread can access this resource until the target thread is resumed. If 1118 * the thread that would resume the target thread attempts to lock this 1119 * monitor prior to calling {@code resume}, deadlock results. Such 1120 * deadlocks typically manifest themselves as "frozen" processes. 1121 * For more information, see 1122 * <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why 1123 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>. 1124 */ 1125 @Deprecated(since="1.2") 1126 public final void suspend() { 1127 checkAccess(); 1128 suspend0(); 1129 } 1130 1131 /** 1132 * Resumes a suspended thread. 1133 * <p> 1134 * First, the {@code checkAccess} method of this thread is called 1135 * with no arguments. This may result in throwing a 1136 * {@code SecurityException} (in the current thread). 1137 * <p> 1138 * If the thread is alive but suspended, it is resumed and is 1139 * permitted to make progress in its execution. 1140 * 1141 * @throws SecurityException if the current thread cannot modify this 1142 * thread. 1143 * @see #checkAccess 1144 * @see #suspend() 1145 * @deprecated This method exists solely for use with {@link #suspend}, 1146 * which has been deprecated because it is deadlock-prone. 1147 * For more information, see 1148 * <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why 1149 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>. 1150 */ 1151 @Deprecated(since="1.2") 1152 public final void resume() { 1153 checkAccess(); 1154 resume0(); 1155 } 1156 1157 /** 1158 * Changes the priority of this thread. 1159 * <p> 1160 * First the {@code checkAccess} method of this thread is called 1161 * with no arguments. This may result in throwing a {@code SecurityException}. 1162 * <p> 1163 * Otherwise, the priority of this thread is set to the smaller of 1164 * the specified {@code newPriority} and the maximum permitted 1165 * priority of the thread's thread group. 1166 * 1167 * @param newPriority priority to set this thread to 1168 * @throws IllegalArgumentException If the priority is not in the 1169 * range {@code MIN_PRIORITY} to 1170 * {@code MAX_PRIORITY}. 1171 * @throws SecurityException if the current thread cannot modify 1172 * this thread. 1173 * @see #getPriority 1174 * @see #checkAccess() 1175 * @see #getThreadGroup() 1176 * @see #MAX_PRIORITY 1177 * @see #MIN_PRIORITY 1178 * @see ThreadGroup#getMaxPriority() 1179 */ 1180 public final void setPriority(int newPriority) { 1181 ThreadGroup g; 1182 checkAccess(); 1183 if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) { 1184 throw new IllegalArgumentException(); 1185 } 1186 if((g = getThreadGroup()) != null) { 1187 if (newPriority > g.getMaxPriority()) { 1188 newPriority = g.getMaxPriority(); 1189 } 1190 setPriority0(priority = newPriority); 1191 } 1192 } 1193 1194 /** 1195 * Returns this thread's priority. 1196 * 1197 * @return this thread's priority. 1198 * @see #setPriority 1199 */ 1200 public final int getPriority() { 1201 return priority; 1202 } 1203 1204 /** 1205 * Changes the name of this thread to be equal to the argument {@code name}. 1206 * <p> 1207 * First the {@code checkAccess} method of this thread is called 1208 * with no arguments. This may result in throwing a 1209 * {@code SecurityException}. 1210 * 1211 * @param name the new name for this thread. 1212 * @throws SecurityException if the current thread cannot modify this 1213 * thread. 1214 * @see #getName 1215 * @see #checkAccess() 1216 */ 1217 public final synchronized void setName(String name) { 1218 checkAccess(); 1219 if (name == null) { 1220 throw new NullPointerException("name cannot be null"); 1221 } 1222 1223 this.name = name; 1224 if (threadStatus != 0) { 1225 setNativeName(name); 1226 } 1227 } 1228 1229 /** 1230 * Returns this thread's name. 1231 * 1232 * @return this thread's name. 1233 * @see #setName(String) 1234 */ 1235 public final String getName() { 1236 return name; 1237 } 1238 1239 /** 1240 * Returns the thread group to which this thread belongs. 1241 * This method returns null if this thread has died 1242 * (been stopped). 1243 * 1244 * @return this thread's thread group. 1245 */ 1246 public final ThreadGroup getThreadGroup() { 1247 return group; 1248 } 1249 1250 /** 1251 * Returns an estimate of the number of active threads in the current 1252 * thread's {@linkplain java.lang.ThreadGroup thread group} and its 1253 * subgroups. Recursively iterates over all subgroups in the current 1254 * thread's thread group. 1255 * 1256 * <p> The value returned is only an estimate because the number of 1257 * threads may change dynamically while this method traverses internal 1258 * data structures, and might be affected by the presence of certain 1259 * system threads. This method is intended primarily for debugging 1260 * and monitoring purposes. 1261 * 1262 * @return an estimate of the number of active threads in the current 1263 * thread's thread group and in any other thread group that 1264 * has the current thread's thread group as an ancestor 1265 */ 1266 public static int activeCount() { 1267 return currentThread().getThreadGroup().activeCount(); 1268 } 1269 1270 /** 1271 * Copies into the specified array every active thread in the current 1272 * thread's thread group and its subgroups. This method simply 1273 * invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])} 1274 * method of the current thread's thread group. 1275 * 1276 * <p> An application might use the {@linkplain #activeCount activeCount} 1277 * method to get an estimate of how big the array should be, however 1278 * <i>if the array is too short to hold all the threads, the extra threads 1279 * are silently ignored.</i> If it is critical to obtain every active 1280 * thread in the current thread's thread group and its subgroups, the 1281 * invoker should verify that the returned int value is strictly less 1282 * than the length of {@code tarray}. 1283 * 1284 * <p> Due to the inherent race condition in this method, it is recommended 1285 * that the method only be used for debugging and monitoring purposes. 1286 * 1287 * @param tarray 1288 * an array into which to put the list of threads 1289 * 1290 * @return the number of threads put into the array 1291 * 1292 * @throws SecurityException 1293 * if {@link java.lang.ThreadGroup#checkAccess} determines that 1294 * the current thread cannot access its thread group 1295 */ 1296 public static int enumerate(Thread tarray[]) { 1297 return currentThread().getThreadGroup().enumerate(tarray); 1298 } 1299 1300 /** 1301 * Counts the number of stack frames in this thread. The thread must 1302 * be suspended. 1303 * 1304 * @return the number of stack frames in this thread. 1305 * @throws IllegalThreadStateException if this thread is not 1306 * suspended. 1307 * @deprecated The definition of this call depends on {@link #suspend}, 1308 * which is deprecated. Further, the results of this call 1309 * were never well-defined. 1310 * This method is subject to removal in a future version of Java SE. 1311 * @see StackWalker 1312 */ 1313 @Deprecated(since="1.2", forRemoval=true) 1314 public native int countStackFrames(); 1315 1316 /** 1317 * Waits at most {@code millis} milliseconds for this thread to 1318 * die. A timeout of {@code 0} means to wait forever. 1319 * 1320 * <p> This implementation uses a loop of {@code this.wait} calls 1321 * conditioned on {@code this.isAlive}. As a thread terminates the 1322 * {@code this.notifyAll} method is invoked. It is recommended that 1323 * applications not use {@code wait}, {@code notify}, or 1324 * {@code notifyAll} on {@code Thread} instances. 1325 * 1326 * @param millis 1327 * the time to wait in milliseconds 1328 * 1329 * @throws IllegalArgumentException 1330 * if the value of {@code millis} is negative 1331 * 1332 * @throws InterruptedException 1333 * if any thread has interrupted the current thread. The 1334 * <i>interrupted status</i> of the current thread is 1335 * cleared when this exception is thrown. 1336 */ 1337 public final synchronized void join(long millis) 1338 throws InterruptedException { 1339 long base = System.currentTimeMillis(); 1340 long now = 0; 1341 1342 if (millis < 0) { 1343 throw new IllegalArgumentException("timeout value is negative"); 1344 } 1345 1346 if (millis == 0) { 1347 while (isAlive()) { 1348 wait(0); 1349 } 1350 } else { 1351 while (isAlive()) { 1352 long delay = millis - now; 1353 if (delay <= 0) { 1354 break; 1355 } 1356 wait(delay); 1357 now = System.currentTimeMillis() - base; 1358 } 1359 } 1360 } 1361 1362 /** 1363 * Waits at most {@code millis} milliseconds plus 1364 * {@code nanos} nanoseconds for this thread to die. 1365 * 1366 * <p> This implementation uses a loop of {@code this.wait} calls 1367 * conditioned on {@code this.isAlive}. As a thread terminates the 1368 * {@code this.notifyAll} method is invoked. It is recommended that 1369 * applications not use {@code wait}, {@code notify}, or 1370 * {@code notifyAll} on {@code Thread} instances. 1371 * 1372 * @param millis 1373 * the time to wait in milliseconds 1374 * 1375 * @param nanos 1376 * {@code 0-999999} additional nanoseconds to wait 1377 * 1378 * @throws IllegalArgumentException 1379 * if the value of {@code millis} is negative, or the value 1380 * of {@code nanos} is not in the range {@code 0-999999} 1381 * 1382 * @throws InterruptedException 1383 * if any thread has interrupted the current thread. The 1384 * <i>interrupted status</i> of the current thread is 1385 * cleared when this exception is thrown. 1386 */ 1387 public final synchronized void join(long millis, int nanos) 1388 throws InterruptedException { 1389 1390 if (millis < 0) { 1391 throw new IllegalArgumentException("timeout value is negative"); 1392 } 1393 1394 if (nanos < 0 || nanos > 999999) { 1395 throw new IllegalArgumentException( 1396 "nanosecond timeout value out of range"); 1397 } 1398 1399 if (nanos >= 500000 || (nanos != 0 && millis == 0)) { 1400 millis++; 1401 } 1402 1403 join(millis); 1404 } 1405 1406 /** 1407 * Waits for this thread to die. 1408 * 1409 * <p> An invocation of this method behaves in exactly the same 1410 * way as the invocation 1411 * 1412 * <blockquote> 1413 * {@linkplain #join(long) join}{@code (0)} 1414 * </blockquote> 1415 * 1416 * @throws InterruptedException 1417 * if any thread has interrupted the current thread. The 1418 * <i>interrupted status</i> of the current thread is 1419 * cleared when this exception is thrown. 1420 */ 1421 public final void join() throws InterruptedException { 1422 join(0); 1423 } 1424 1425 /** 1426 * Prints a stack trace of the current thread to the standard error stream. 1427 * This method is used only for debugging. 1428 */ 1429 public static void dumpStack() { 1430 new Exception("Stack trace").printStackTrace(); 1431 } 1432 1433 /** 1434 * Marks this thread as either a {@linkplain #isDaemon daemon} thread 1435 * or a user thread. The Java Virtual Machine exits when the only 1436 * threads running are all daemon threads. 1437 * 1438 * <p> This method must be invoked before the thread is started. 1439 * 1440 * @param on 1441 * if {@code true}, marks this thread as a daemon thread 1442 * 1443 * @throws IllegalThreadStateException 1444 * if this thread is {@linkplain #isAlive alive} 1445 * 1446 * @throws SecurityException 1447 * if {@link #checkAccess} determines that the current 1448 * thread cannot modify this thread 1449 */ 1450 public final void setDaemon(boolean on) { 1451 checkAccess(); 1452 if (isAlive()) { 1453 throw new IllegalThreadStateException(); 1454 } 1455 daemon = on; 1456 } 1457 1458 /** 1459 * Tests if this thread is a daemon thread. 1460 * 1461 * @return {@code true} if this thread is a daemon thread; 1462 * {@code false} otherwise. 1463 * @see #setDaemon(boolean) 1464 */ 1465 public final boolean isDaemon() { 1466 return daemon; 1467 } 1468 1469 /** 1470 * Determines if the currently running thread has permission to 1471 * modify this thread. 1472 * <p> 1473 * If there is a security manager, its {@code checkAccess} method 1474 * is called with this thread as its argument. This may result in 1475 * throwing a {@code SecurityException}. 1476 * 1477 * @throws SecurityException if the current thread is not allowed to 1478 * access this thread. 1479 * @see SecurityManager#checkAccess(Thread) 1480 */ 1481 public final void checkAccess() { 1482 SecurityManager security = System.getSecurityManager(); 1483 if (security != null) { 1484 security.checkAccess(this); 1485 } 1486 } 1487 1488 /** 1489 * Returns a string representation of this thread, including the 1490 * thread's name, priority, and thread group. 1491 * 1492 * @return a string representation of this thread. 1493 */ 1494 public String toString() { 1495 ThreadGroup group = getThreadGroup(); 1496 if (group != null) { 1497 return "Thread[" + getName() + "," + getPriority() + "," + 1498 group.getName() + "]"; 1499 } else { 1500 return "Thread[" + getName() + "," + getPriority() + "," + 1501 "" + "]"; 1502 } 1503 } 1504 1505 /** 1506 * Returns the context {@code ClassLoader} for this thread. The context 1507 * {@code ClassLoader} is provided by the creator of the thread for use 1508 * by code running in this thread when loading classes and resources. 1509 * If not {@linkplain #setContextClassLoader set}, the default is the 1510 * {@code ClassLoader} context of the parent thread. The context 1511 * {@code ClassLoader} of the 1512 * primordial thread is typically set to the class loader used to load the 1513 * application. 1514 * 1515 * 1516 * @return the context {@code ClassLoader} for this thread, or {@code null} 1517 * indicating the system class loader (or, failing that, the 1518 * bootstrap class loader) 1519 * 1520 * @throws SecurityException 1521 * if a security manager is present, and the caller's class loader 1522 * is not {@code null} and is not the same as or an ancestor of the 1523 * context class loader, and the caller does not have the 1524 * {@link RuntimePermission}{@code ("getClassLoader")} 1525 * 1526 * @since 1.2 1527 */ 1528 @CallerSensitive 1529 public ClassLoader getContextClassLoader() { 1530 if (contextClassLoader == null) 1531 return null; 1532 SecurityManager sm = System.getSecurityManager(); 1533 if (sm != null) { 1534 ClassLoader.checkClassLoaderPermission(contextClassLoader, 1535 Reflection.getCallerClass()); 1536 } 1537 return contextClassLoader; 1538 } 1539 1540 /** 1541 * Sets the context ClassLoader for this Thread. The context 1542 * ClassLoader can be set when a thread is created, and allows 1543 * the creator of the thread to provide the appropriate class loader, 1544 * through {@code getContextClassLoader}, to code running in the thread 1545 * when loading classes and resources. 1546 * 1547 * <p>If a security manager is present, its {@link 1548 * SecurityManager#checkPermission(java.security.Permission) checkPermission} 1549 * method is invoked with a {@link RuntimePermission RuntimePermission}{@code 1550 * ("setContextClassLoader")} permission to see if setting the context 1551 * ClassLoader is permitted. 1552 * 1553 * @param cl 1554 * the context ClassLoader for this Thread, or null indicating the 1555 * system class loader (or, failing that, the bootstrap class loader) 1556 * 1557 * @throws SecurityException 1558 * if the current thread cannot set the context ClassLoader 1559 * 1560 * @since 1.2 1561 */ 1562 public void setContextClassLoader(ClassLoader cl) { 1563 SecurityManager sm = System.getSecurityManager(); 1564 if (sm != null) { 1565 sm.checkPermission(new RuntimePermission("setContextClassLoader")); 1566 } 1567 contextClassLoader = cl; 1568 } 1569 1570 /** 1571 * Returns {@code true} if and only if the current thread holds the 1572 * monitor lock on the specified object. 1573 * 1574 * <p>This method is designed to allow a program to assert that 1575 * the current thread already holds a specified lock: 1576 * <pre> 1577 * assert Thread.holdsLock(obj); 1578 * </pre> 1579 * 1580 * @param obj the object on which to test lock ownership 1581 * @throws NullPointerException if obj is {@code null} 1582 * @return {@code true} if the current thread holds the monitor lock on 1583 * the specified object. 1584 * @since 1.4 1585 */ 1586 public static native boolean holdsLock(Object obj); 1587 1588 private static final StackTraceElement[] EMPTY_STACK_TRACE 1589 = new StackTraceElement[0]; 1590 1591 /** 1592 * Returns an array of stack trace elements representing the stack dump 1593 * of this thread. This method will return a zero-length array if 1594 * this thread has not started, has started but has not yet been 1595 * scheduled to run by the system, or has terminated. 1596 * If the returned array is of non-zero length then the first element of 1597 * the array represents the top of the stack, which is the most recent 1598 * method invocation in the sequence. The last element of the array 1599 * represents the bottom of the stack, which is the least recent method 1600 * invocation in the sequence. 1601 * 1602 * <p>If there is a security manager, and this thread is not 1603 * the current thread, then the security manager's 1604 * {@code checkPermission} method is called with a 1605 * {@code RuntimePermission("getStackTrace")} permission 1606 * to see if it's ok to get the stack trace. 1607 * 1608 * <p>Some virtual machines may, under some circumstances, omit one 1609 * or more stack frames from the stack trace. In the extreme case, 1610 * a virtual machine that has no stack trace information concerning 1611 * this thread is permitted to return a zero-length array from this 1612 * method. 1613 * 1614 * @return an array of {@code StackTraceElement}, 1615 * each represents one stack frame. 1616 * 1617 * @throws SecurityException 1618 * if a security manager exists and its 1619 * {@code checkPermission} method doesn't allow 1620 * getting the stack trace of thread. 1621 * @see SecurityManager#checkPermission 1622 * @see RuntimePermission 1623 * @see Throwable#getStackTrace 1624 * 1625 * @since 1.5 1626 */ 1627 public StackTraceElement[] getStackTrace() { 1628 if (this != Thread.currentThread()) { 1629 // check for getStackTrace permission 1630 SecurityManager security = System.getSecurityManager(); 1631 if (security != null) { 1632 security.checkPermission( 1633 SecurityConstants.GET_STACK_TRACE_PERMISSION); 1634 } 1635 // optimization so we do not call into the vm for threads that 1636 // have not yet started or have terminated 1637 if (!isAlive()) { 1638 return EMPTY_STACK_TRACE; 1639 } 1640 StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this}); 1641 StackTraceElement[] stackTrace = stackTraceArray[0]; 1642 // a thread that was alive during the previous isAlive call may have 1643 // since terminated, therefore not having a stacktrace. 1644 if (stackTrace == null) { 1645 stackTrace = EMPTY_STACK_TRACE; 1646 } 1647 return stackTrace; 1648 } else { 1649 return (new Exception()).getStackTrace(); 1650 } 1651 } 1652 1653 /** 1654 * Returns a map of stack traces for all live threads. 1655 * The map keys are threads and each map value is an array of 1656 * {@code StackTraceElement} that represents the stack dump 1657 * of the corresponding {@code Thread}. 1658 * The returned stack traces are in the format specified for 1659 * the {@link #getStackTrace getStackTrace} method. 1660 * 1661 * <p>The threads may be executing while this method is called. 1662 * The stack trace of each thread only represents a snapshot and 1663 * each stack trace may be obtained at different time. A zero-length 1664 * array will be returned in the map value if the virtual machine has 1665 * no stack trace information about a thread. 1666 * 1667 * <p>If there is a security manager, then the security manager's 1668 * {@code checkPermission} method is called with a 1669 * {@code RuntimePermission("getStackTrace")} permission as well as 1670 * {@code RuntimePermission("modifyThreadGroup")} permission 1671 * to see if it is ok to get the stack trace of all threads. 1672 * 1673 * @return a {@code Map} from {@code Thread} to an array of 1674 * {@code StackTraceElement} that represents the stack trace of 1675 * the corresponding thread. 1676 * 1677 * @throws SecurityException 1678 * if a security manager exists and its 1679 * {@code checkPermission} method doesn't allow 1680 * getting the stack trace of thread. 1681 * @see #getStackTrace 1682 * @see SecurityManager#checkPermission 1683 * @see RuntimePermission 1684 * @see Throwable#getStackTrace 1685 * 1686 * @since 1.5 1687 */ 1688 public static Map<Thread, StackTraceElement[]> getAllStackTraces() { 1689 // check for getStackTrace permission 1690 SecurityManager security = System.getSecurityManager(); 1691 if (security != null) { 1692 security.checkPermission( 1693 SecurityConstants.GET_STACK_TRACE_PERMISSION); 1694 security.checkPermission( 1695 SecurityConstants.MODIFY_THREADGROUP_PERMISSION); 1696 } 1697 1698 // Get a snapshot of the list of all threads 1699 Thread[] threads = getThreads(); 1700 StackTraceElement[][] traces = dumpThreads(threads); 1701 Map<Thread, StackTraceElement[]> m = new HashMap<>(threads.length); 1702 for (int i = 0; i < threads.length; i++) { 1703 StackTraceElement[] stackTrace = traces[i]; 1704 if (stackTrace != null) { 1705 m.put(threads[i], stackTrace); 1706 } 1707 // else terminated so we don't put it in the map 1708 } 1709 return m; 1710 } 1711 1712 /** cache of subclass security audit results */ 1713 /* Replace with ConcurrentReferenceHashMap when/if it appears in a future 1714 * release */ 1715 private static class Caches { 1716 /** cache of subclass security audit results */ 1717 static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits = 1718 new ConcurrentHashMap<>(); 1719 1720 /** queue for WeakReferences to audited subclasses */ 1721 static final ReferenceQueue<Class<?>> subclassAuditsQueue = 1722 new ReferenceQueue<>(); 1723 } 1724 1725 /** 1726 * Verifies that this (possibly subclass) instance can be constructed 1727 * without violating security constraints: the subclass must not override 1728 * security-sensitive non-final methods, or else the 1729 * "enableContextClassLoaderOverride" RuntimePermission is checked. 1730 */ 1731 private static boolean isCCLOverridden(Class<?> cl) { 1732 if (cl == Thread.class) 1733 return false; 1734 1735 processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits); 1736 WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue); 1737 Boolean result = Caches.subclassAudits.get(key); 1738 if (result == null) { 1739 result = Boolean.valueOf(auditSubclass(cl)); 1740 Caches.subclassAudits.putIfAbsent(key, result); 1741 } 1742 1743 return result.booleanValue(); 1744 } 1745 1746 /** 1747 * Performs reflective checks on given subclass to verify that it doesn't 1748 * override security-sensitive non-final methods. Returns true if the 1749 * subclass overrides any of the methods, false otherwise. 1750 */ 1751 private static boolean auditSubclass(final Class<?> subcl) { 1752 Boolean result = AccessController.doPrivileged( 1753 new PrivilegedAction<>() { 1754 public Boolean run() { 1755 for (Class<?> cl = subcl; 1756 cl != Thread.class; 1757 cl = cl.getSuperclass()) 1758 { 1759 try { 1760 cl.getDeclaredMethod("getContextClassLoader", new Class<?>[0]); 1761 return Boolean.TRUE; 1762 } catch (NoSuchMethodException ex) { 1763 } 1764 try { 1765 Class<?>[] params = {ClassLoader.class}; 1766 cl.getDeclaredMethod("setContextClassLoader", params); 1767 return Boolean.TRUE; 1768 } catch (NoSuchMethodException ex) { 1769 } 1770 } 1771 return Boolean.FALSE; 1772 } 1773 } 1774 ); 1775 return result.booleanValue(); 1776 } 1777 1778 private static native StackTraceElement[][] dumpThreads(Thread[] threads); 1779 private static native Thread[] getThreads(); 1780 1781 /** 1782 * Returns the identifier of this Thread. The thread ID is a positive 1783 * {@code long} number generated when this thread was created. 1784 * The thread ID is unique and remains unchanged during its lifetime. 1785 * When a thread is terminated, this thread ID may be reused. 1786 * 1787 * @return this thread's ID. 1788 * @since 1.5 1789 */ 1790 public long getId() { 1791 return tid; 1792 } 1793 1794 /** 1795 * A thread state. A thread can be in one of the following states: 1796 * <ul> 1797 * <li>{@link #NEW}<br> 1798 * A thread that has not yet started is in this state. 1799 * </li> 1800 * <li>{@link #RUNNABLE}<br> 1801 * A thread executing in the Java virtual machine is in this state. 1802 * </li> 1803 * <li>{@link #BLOCKED}<br> 1804 * A thread that is blocked waiting for a monitor lock 1805 * is in this state. 1806 * </li> 1807 * <li>{@link #WAITING}<br> 1808 * A thread that is waiting indefinitely for another thread to 1809 * perform a particular action is in this state. 1810 * </li> 1811 * <li>{@link #TIMED_WAITING}<br> 1812 * A thread that is waiting for another thread to perform an action 1813 * for up to a specified waiting time is in this state. 1814 * </li> 1815 * <li>{@link #TERMINATED}<br> 1816 * A thread that has exited is in this state. 1817 * </li> 1818 * </ul> 1819 * 1820 * <p> 1821 * A thread can be in only one state at a given point in time. 1822 * These states are virtual machine states which do not reflect 1823 * any operating system thread states. 1824 * 1825 * @since 1.5 1826 * @see #getState 1827 */ 1828 public enum State { 1829 /** 1830 * Thread state for a thread which has not yet started. 1831 */ 1832 NEW, 1833 1834 /** 1835 * Thread state for a runnable thread. A thread in the runnable 1836 * state is executing in the Java virtual machine but it may 1837 * be waiting for other resources from the operating system 1838 * such as processor. 1839 */ 1840 RUNNABLE, 1841 1842 /** 1843 * Thread state for a thread blocked waiting for a monitor lock. 1844 * A thread in the blocked state is waiting for a monitor lock 1845 * to enter a synchronized block/method or 1846 * reenter a synchronized block/method after calling 1847 * {@link Object#wait() Object.wait}. 1848 */ 1849 BLOCKED, 1850 1851 /** 1852 * Thread state for a waiting thread. 1853 * A thread is in the waiting state due to calling one of the 1854 * following methods: 1855 * <ul> 1856 * <li>{@link Object#wait() Object.wait} with no timeout</li> 1857 * <li>{@link #join() Thread.join} with no timeout</li> 1858 * <li>{@link LockSupport#park() LockSupport.park}</li> 1859 * </ul> 1860 * 1861 * <p>A thread in the waiting state is waiting for another thread to 1862 * perform a particular action. 1863 * 1864 * For example, a thread that has called {@code Object.wait()} 1865 * on an object is waiting for another thread to call 1866 * {@code Object.notify()} or {@code Object.notifyAll()} on 1867 * that object. A thread that has called {@code Thread.join()} 1868 * is waiting for a specified thread to terminate. 1869 */ 1870 WAITING, 1871 1872 /** 1873 * Thread state for a waiting thread with a specified waiting time. 1874 * A thread is in the timed waiting state due to calling one of 1875 * the following methods with a specified positive waiting time: 1876 * <ul> 1877 * <li>{@link #sleep Thread.sleep}</li> 1878 * <li>{@link Object#wait(long) Object.wait} with timeout</li> 1879 * <li>{@link #join(long) Thread.join} with timeout</li> 1880 * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> 1881 * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li> 1882 * </ul> 1883 */ 1884 TIMED_WAITING, 1885 1886 /** 1887 * Thread state for a terminated thread. 1888 * The thread has completed execution. 1889 */ 1890 TERMINATED; 1891 } 1892 1893 /** 1894 * Returns the state of this thread. 1895 * This method is designed for use in monitoring of the system state, 1896 * not for synchronization control. 1897 * 1898 * @return this thread's state. 1899 * @since 1.5 1900 */ 1901 public State getState() { 1902 // get current thread state 1903 return jdk.internal.misc.VM.toThreadState(threadStatus); 1904 } 1905 1906 // Added in JSR-166 1907 1908 /** 1909 * Interface for handlers invoked when a {@code Thread} abruptly 1910 * terminates due to an uncaught exception. 1911 * <p>When a thread is about to terminate due to an uncaught exception 1912 * the Java Virtual Machine will query the thread for its 1913 * {@code UncaughtExceptionHandler} using 1914 * {@link #getUncaughtExceptionHandler} and will invoke the handler's 1915 * {@code uncaughtException} method, passing the thread and the 1916 * exception as arguments. 1917 * If a thread has not had its {@code UncaughtExceptionHandler} 1918 * explicitly set, then its {@code ThreadGroup} object acts as its 1919 * {@code UncaughtExceptionHandler}. If the {@code ThreadGroup} object 1920 * has no 1921 * special requirements for dealing with the exception, it can forward 1922 * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler 1923 * default uncaught exception handler}. 1924 * 1925 * @see #setDefaultUncaughtExceptionHandler 1926 * @see #setUncaughtExceptionHandler 1927 * @see ThreadGroup#uncaughtException 1928 * @since 1.5 1929 */ 1930 @FunctionalInterface 1931 public interface UncaughtExceptionHandler { 1932 /** 1933 * Method invoked when the given thread terminates due to the 1934 * given uncaught exception. 1935 * <p>Any exception thrown by this method will be ignored by the 1936 * Java Virtual Machine. 1937 * @param t the thread 1938 * @param e the exception 1939 */ 1940 void uncaughtException(Thread t, Throwable e); 1941 } 1942 1943 // null unless explicitly set 1944 private volatile UncaughtExceptionHandler uncaughtExceptionHandler; 1945 1946 // null unless explicitly set 1947 private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler; 1948 1949 /** 1950 * Set the default handler invoked when a thread abruptly terminates 1951 * due to an uncaught exception, and no other handler has been defined 1952 * for that thread. 1953 * 1954 * <p>Uncaught exception handling is controlled first by the thread, then 1955 * by the thread's {@link ThreadGroup} object and finally by the default 1956 * uncaught exception handler. If the thread does not have an explicit 1957 * uncaught exception handler set, and the thread's thread group 1958 * (including parent thread groups) does not specialize its 1959 * {@code uncaughtException} method, then the default handler's 1960 * {@code uncaughtException} method will be invoked. 1961 * <p>By setting the default uncaught exception handler, an application 1962 * can change the way in which uncaught exceptions are handled (such as 1963 * logging to a specific device, or file) for those threads that would 1964 * already accept whatever "default" behavior the system 1965 * provided. 1966 * 1967 * <p>Note that the default uncaught exception handler should not usually 1968 * defer to the thread's {@code ThreadGroup} object, as that could cause 1969 * infinite recursion. 1970 * 1971 * @param eh the object to use as the default uncaught exception handler. 1972 * If {@code null} then there is no default handler. 1973 * 1974 * @throws SecurityException if a security manager is present and it denies 1975 * {@link RuntimePermission}{@code ("setDefaultUncaughtExceptionHandler")} 1976 * 1977 * @see #setUncaughtExceptionHandler 1978 * @see #getUncaughtExceptionHandler 1979 * @see ThreadGroup#uncaughtException 1980 * @since 1.5 1981 */ 1982 public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) { 1983 SecurityManager sm = System.getSecurityManager(); 1984 if (sm != null) { 1985 sm.checkPermission( 1986 new RuntimePermission("setDefaultUncaughtExceptionHandler") 1987 ); 1988 } 1989 1990 defaultUncaughtExceptionHandler = eh; 1991 } 1992 1993 /** 1994 * Returns the default handler invoked when a thread abruptly terminates 1995 * due to an uncaught exception. If the returned value is {@code null}, 1996 * there is no default. 1997 * @since 1.5 1998 * @see #setDefaultUncaughtExceptionHandler 1999 * @return the default uncaught exception handler for all threads 2000 */ 2001 public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){ 2002 return defaultUncaughtExceptionHandler; 2003 } 2004 2005 /** 2006 * Returns the handler invoked when this thread abruptly terminates 2007 * due to an uncaught exception. If this thread has not had an 2008 * uncaught exception handler explicitly set then this thread's 2009 * {@code ThreadGroup} object is returned, unless this thread 2010 * has terminated, in which case {@code null} is returned. 2011 * @since 1.5 2012 * @return the uncaught exception handler for this thread 2013 */ 2014 public UncaughtExceptionHandler getUncaughtExceptionHandler() { 2015 return uncaughtExceptionHandler != null ? 2016 uncaughtExceptionHandler : group; 2017 } 2018 2019 /** 2020 * Set the handler invoked when this thread abruptly terminates 2021 * due to an uncaught exception. 2022 * <p>A thread can take full control of how it responds to uncaught 2023 * exceptions by having its uncaught exception handler explicitly set. 2024 * If no such handler is set then the thread's {@code ThreadGroup} 2025 * object acts as its handler. 2026 * @param eh the object to use as this thread's uncaught exception 2027 * handler. If {@code null} then this thread has no explicit handler. 2028 * @throws SecurityException if the current thread is not allowed to 2029 * modify this thread. 2030 * @see #setDefaultUncaughtExceptionHandler 2031 * @see ThreadGroup#uncaughtException 2032 * @since 1.5 2033 */ 2034 public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) { 2035 checkAccess(); 2036 uncaughtExceptionHandler = eh; 2037 } 2038 2039 /** 2040 * Dispatch an uncaught exception to the handler. This method is 2041 * intended to be called only by the JVM. 2042 */ 2043 private void dispatchUncaughtException(Throwable e) { 2044 getUncaughtExceptionHandler().uncaughtException(this, e); 2045 } 2046 2047 /** 2048 * Removes from the specified map any keys that have been enqueued 2049 * on the specified reference queue. 2050 */ 2051 static void processQueue(ReferenceQueue<Class<?>> queue, 2052 ConcurrentMap<? extends 2053 WeakReference<Class<?>>, ?> map) 2054 { 2055 Reference<? extends Class<?>> ref; 2056 while((ref = queue.poll()) != null) { 2057 map.remove(ref); 2058 } 2059 } 2060 2061 /** 2062 * Weak key for Class objects. 2063 **/ 2064 static class WeakClassKey extends WeakReference<Class<?>> { 2065 /** 2066 * saved value of the referent's identity hash code, to maintain 2067 * a consistent hash code after the referent has been cleared 2068 */ 2069 private final int hash; 2070 2071 /** 2072 * Create a new WeakClassKey to the given object, registered 2073 * with a queue. 2074 */ 2075 WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) { 2076 super(cl, refQueue); 2077 hash = System.identityHashCode(cl); 2078 } 2079 2080 /** 2081 * Returns the identity hash code of the original referent. 2082 */ 2083 @Override 2084 public int hashCode() { 2085 return hash; 2086 } 2087 2088 /** 2089 * Returns true if the given object is this identical 2090 * WeakClassKey instance, or, if this object's referent has not 2091 * been cleared, if the given object is another WeakClassKey 2092 * instance with the identical non-null referent as this one. 2093 */ 2094 @Override 2095 public boolean equals(Object obj) { 2096 if (obj == this) 2097 return true; 2098 2099 if (obj instanceof WeakClassKey) { 2100 Object referent = get(); 2101 return (referent != null) && 2102 (referent == ((WeakClassKey) obj).get()); 2103 } else { 2104 return false; 2105 } 2106 } 2107 } 2108 2109 2110 // The following three initially uninitialized fields are exclusively 2111 // managed by class java.util.concurrent.ThreadLocalRandom. These 2112 // fields are used to build the high-performance PRNGs in the 2113 // concurrent code, and we can not risk accidental false sharing. 2114 // Hence, the fields are isolated with @Contended. 2115 2116 /** The current seed for a ThreadLocalRandom */ 2117 @jdk.internal.vm.annotation.Contended("tlr") 2118 long threadLocalRandomSeed; 2119 2120 /** Probe hash value; nonzero if threadLocalRandomSeed initialized */ 2121 @jdk.internal.vm.annotation.Contended("tlr") 2122 int threadLocalRandomProbe; 2123 2124 /** Secondary seed isolated from public ThreadLocalRandom sequence */ 2125 @jdk.internal.vm.annotation.Contended("tlr") 2126 int threadLocalRandomSecondarySeed; 2127 2128 /* Some private helper methods */ 2129 private native void setPriority0(int newPriority); 2130 private native void stop0(Object o); 2131 private native void suspend0(); 2132 private native void resume0(); 2133 private native void interrupt0(); 2134 private native void setNativeName(String name); 2135 }