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