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