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