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