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