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