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