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