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