1 /* 2 * Copyright (c) 1994, 2010, 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 } 1140 1141 /** 1142 * Returns this thread's name. 1143 * 1144 * @return this thread's name. 1145 * @see #setName(String) 1146 */ 1147 public final String getName() { 1148 return String.valueOf(name); 1149 } 1150 1151 /** 1152 * Returns the thread group to which this thread belongs. 1153 * This method returns null if this thread has died 1154 * (been stopped). 1155 * 1156 * @return this thread's thread group. 1157 */ 1158 public final ThreadGroup getThreadGroup() { 1159 return group; 1160 } 1161 1162 /** 1163 * Returns an estimate of the number of active threads in the current 1164 * thread's {@linkplain java.lang.ThreadGroup thread group} and its 1165 * subgroups. Recursively iterates over all subgroups in the current 1166 * thread's thread group. 1167 * 1168 * <p> The value returned is only an estimate because the number of 1169 * threads may change dynamically while this method traverses internal 1170 * data structures, and might be affected by the presence of certain 1171 * system threads. This method is intended primarily for debugging 1172 * and monitoring purposes. 1173 * 1174 * @return an estimate of the number of active threads in the current 1175 * thread's thread group and in any other thread group that 1176 * has the current thread's thread group as an ancestor 1177 */ 1178 public static int activeCount() { 1179 return currentThread().getThreadGroup().activeCount(); 1180 } 1181 1182 /** 1183 * Copies into the specified array every active thread in the current 1184 * thread's thread group and its subgroups. This method simply 1185 * invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])} 1186 * method of the current thread's thread group. 1187 * 1188 * <p> An application might use the {@linkplain #activeCount activeCount} 1189 * method to get an estimate of how big the array should be, however 1190 * <i>if the array is too short to hold all the threads, the extra threads 1191 * are silently ignored.</i> If it is critical to obtain every active 1192 * thread in the current thread's thread group and its subgroups, the 1193 * invoker should verify that the returned int value is strictly less 1194 * than the length of {@code tarray}. 1195 * 1196 * <p> Due to the inherent race condition in this method, it is recommended 1197 * that the method only be used for debugging and monitoring purposes. 1198 * 1199 * @param tarray 1200 * an array into which to put the list of threads 1201 * 1202 * @return the number of threads put into the array 1203 * 1204 * @throws SecurityException 1205 * if {@link java.lang.ThreadGroup#checkAccess} determines that 1206 * the current thread cannot access its thread group 1207 */ 1208 public static int enumerate(Thread tarray[]) { 1209 return currentThread().getThreadGroup().enumerate(tarray); 1210 } 1211 1212 /** 1213 * Counts the number of stack frames in this thread. The thread must 1214 * be suspended. 1215 * 1216 * @return the number of stack frames in this thread. 1217 * @exception IllegalThreadStateException if this thread is not 1218 * suspended. 1219 * @deprecated The definition of this call depends on {@link #suspend}, 1220 * which is deprecated. Further, the results of this call 1221 * were never well-defined. 1222 */ 1223 @Deprecated 1224 public native int countStackFrames(); 1225 1226 /** 1227 * Waits at most {@code millis} milliseconds for this thread to 1228 * die. A timeout of {@code 0} means to wait forever. 1229 * 1230 * <p> This implementation uses a loop of {@code this.wait} calls 1231 * conditioned on {@code this.isAlive}. As a thread terminates the 1232 * {@code this.notifyAll} method is invoked. It is recommended that 1233 * applications not use {@code wait}, {@code notify}, or 1234 * {@code notifyAll} on {@code Thread} instances. 1235 * 1236 * @param millis 1237 * the time to wait in milliseconds 1238 * 1239 * @throws IllegalArgumentException 1240 * if the value of {@code millis} is negative 1241 * 1242 * @throws InterruptedException 1243 * if any thread has interrupted the current thread. The 1244 * <i>interrupted status</i> of the current thread is 1245 * cleared when this exception is thrown. 1246 */ 1247 public final synchronized void join(long millis) 1248 throws InterruptedException { 1249 long base = System.currentTimeMillis(); 1250 long now = 0; 1251 1252 if (millis < 0) { 1253 throw new IllegalArgumentException("timeout value is negative"); 1254 } 1255 1256 if (millis == 0) { 1257 while (isAlive()) { 1258 wait(0); 1259 } 1260 } else { 1261 while (isAlive()) { 1262 long delay = millis - now; 1263 if (delay <= 0) { 1264 break; 1265 } 1266 wait(delay); 1267 now = System.currentTimeMillis() - base; 1268 } 1269 } 1270 } 1271 1272 /** 1273 * Waits at most {@code millis} milliseconds plus 1274 * {@code nanos} nanoseconds for this thread to die. 1275 * 1276 * <p> This implementation uses a loop of {@code this.wait} calls 1277 * conditioned on {@code this.isAlive}. As a thread terminates the 1278 * {@code this.notifyAll} method is invoked. It is recommended that 1279 * applications not use {@code wait}, {@code notify}, or 1280 * {@code notifyAll} on {@code Thread} instances. 1281 * 1282 * @param millis 1283 * the time to wait in milliseconds 1284 * 1285 * @param nanos 1286 * {@code 0-999999} additional nanoseconds to wait 1287 * 1288 * @throws IllegalArgumentException 1289 * if the value of {@code millis} is negative, or the value 1290 * of {@code nanos} is not in the range {@code 0-999999} 1291 * 1292 * @throws InterruptedException 1293 * if any thread has interrupted the current thread. The 1294 * <i>interrupted status</i> of the current thread is 1295 * cleared when this exception is thrown. 1296 */ 1297 public final synchronized void join(long millis, int nanos) 1298 throws InterruptedException { 1299 1300 if (millis < 0) { 1301 throw new IllegalArgumentException("timeout value is negative"); 1302 } 1303 1304 if (nanos < 0 || nanos > 999999) { 1305 throw new IllegalArgumentException( 1306 "nanosecond timeout value out of range"); 1307 } 1308 1309 if (nanos >= 500000 || (nanos != 0 && millis == 0)) { 1310 millis++; 1311 } 1312 1313 join(millis); 1314 } 1315 1316 /** 1317 * Waits for this thread to die. 1318 * 1319 * <p> An invocation of this method behaves in exactly the same 1320 * way as the invocation 1321 * 1322 * <blockquote> 1323 * {@linkplain #join(long) join}{@code (0)} 1324 * </blockquote> 1325 * 1326 * @throws InterruptedException 1327 * if any thread has interrupted the current thread. The 1328 * <i>interrupted status</i> of the current thread is 1329 * cleared when this exception is thrown. 1330 */ 1331 public final void join() throws InterruptedException { 1332 join(0); 1333 } 1334 1335 /** 1336 * Prints a stack trace of the current thread to the standard error stream. 1337 * This method is used only for debugging. 1338 * 1339 * @see Throwable#printStackTrace() 1340 */ 1341 public static void dumpStack() { 1342 new Exception("Stack trace").printStackTrace(); 1343 } 1344 1345 /** 1346 * Marks this thread as either a {@linkplain #isDaemon daemon} thread 1347 * or a user thread. The Java Virtual Machine exits when the only 1348 * threads running are all daemon threads. 1349 * 1350 * <p> This method must be invoked before the thread is started. 1351 * 1352 * @param on 1353 * if {@code true}, marks this thread as a daemon thread 1354 * 1355 * @throws IllegalThreadStateException 1356 * if this thread is {@linkplain #isAlive alive} 1357 * 1358 * @throws SecurityException 1359 * if {@link #checkAccess} determines that the current 1360 * thread cannot modify this thread 1361 */ 1362 public final void setDaemon(boolean on) { 1363 checkAccess(); 1364 if (isAlive()) { 1365 throw new IllegalThreadStateException(); 1366 } 1367 daemon = on; 1368 } 1369 1370 /** 1371 * Tests if this thread is a daemon thread. 1372 * 1373 * @return <code>true</code> if this thread is a daemon thread; 1374 * <code>false</code> otherwise. 1375 * @see #setDaemon(boolean) 1376 */ 1377 public final boolean isDaemon() { 1378 return daemon; 1379 } 1380 1381 /** 1382 * Determines if the currently running thread has permission to 1383 * modify this thread. 1384 * <p> 1385 * If there is a security manager, its <code>checkAccess</code> method 1386 * is called with this thread as its argument. This may result in 1387 * throwing a <code>SecurityException</code>. 1388 * 1389 * @exception SecurityException if the current thread is not allowed to 1390 * access this thread. 1391 * @see SecurityManager#checkAccess(Thread) 1392 */ 1393 public final void checkAccess() { 1394 SecurityManager security = System.getSecurityManager(); 1395 if (security != null) { 1396 security.checkAccess(this); 1397 } 1398 } 1399 1400 /** 1401 * Returns a string representation of this thread, including the 1402 * thread's name, priority, and thread group. 1403 * 1404 * @return a string representation of this thread. 1405 */ 1406 public String toString() { 1407 ThreadGroup group = getThreadGroup(); 1408 if (group != null) { 1409 return "Thread[" + getName() + "," + getPriority() + "," + 1410 group.getName() + "]"; 1411 } else { 1412 return "Thread[" + getName() + "," + getPriority() + "," + 1413 "" + "]"; 1414 } 1415 } 1416 1417 /** 1418 * Returns the context ClassLoader for this Thread. The context 1419 * ClassLoader is provided by the creator of the thread for use 1420 * by code running in this thread when loading classes and resources. 1421 * If not {@linkplain #setContextClassLoader set}, the default is the 1422 * ClassLoader context of the parent Thread. The context ClassLoader of the 1423 * primordial thread is typically set to the class loader used to load the 1424 * application. 1425 * 1426 * <p>If a security manager is present, and the invoker's class loader is not 1427 * {@code null} and is not the same as or an ancestor of the context class 1428 * loader, then this method invokes the security manager's {@link 1429 * SecurityManager#checkPermission(java.security.Permission) checkPermission} 1430 * method with a {@link RuntimePermission RuntimePermission}{@code 1431 * ("getClassLoader")} permission to verify that retrieval of the context 1432 * class loader is permitted. 1433 * 1434 * @return the context ClassLoader for this Thread, or {@code null} 1435 * indicating the system class loader (or, failing that, the 1436 * bootstrap class loader) 1437 * 1438 * @throws SecurityException 1439 * if the current thread cannot get the context ClassLoader 1440 * 1441 * @since 1.2 1442 */ 1443 public ClassLoader getContextClassLoader() { 1444 if (contextClassLoader == null) 1445 return null; 1446 SecurityManager sm = System.getSecurityManager(); 1447 if (sm != null) { 1448 ClassLoader ccl = ClassLoader.getCallerClassLoader(); 1449 if (ccl != null && ccl != contextClassLoader && 1450 !contextClassLoader.isAncestor(ccl)) { 1451 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 1452 } 1453 } 1454 return contextClassLoader; 1455 } 1456 1457 /** 1458 * Sets the context ClassLoader for this Thread. The context 1459 * ClassLoader can be set when a thread is created, and allows 1460 * the creator of the thread to provide the appropriate class loader, 1461 * through {@code getContextClassLoader}, to code running in the thread 1462 * when loading classes and resources. 1463 * 1464 * <p>If a security manager is present, its {@link 1465 * SecurityManager#checkPermission(java.security.Permission) checkPermission} 1466 * method is invoked with a {@link RuntimePermission RuntimePermission}{@code 1467 * ("setContextClassLoader")} permission to see if setting the context 1468 * ClassLoader is permitted. 1469 * 1470 * @param cl 1471 * the context ClassLoader for this Thread, or null indicating the 1472 * system class loader (or, failing that, the bootstrap class loader) 1473 * 1474 * @throws SecurityException 1475 * if the current thread cannot set the context ClassLoader 1476 * 1477 * @since 1.2 1478 */ 1479 public void setContextClassLoader(ClassLoader cl) { 1480 SecurityManager sm = System.getSecurityManager(); 1481 if (sm != null) { 1482 sm.checkPermission(new RuntimePermission("setContextClassLoader")); 1483 } 1484 contextClassLoader = cl; 1485 } 1486 1487 /** 1488 * Returns <tt>true</tt> if and only if the current thread holds the 1489 * monitor lock on the specified object. 1490 * 1491 * <p>This method is designed to allow a program to assert that 1492 * the current thread already holds a specified lock: 1493 * <pre> 1494 * assert Thread.holdsLock(obj); 1495 * </pre> 1496 * 1497 * @param obj the object on which to test lock ownership 1498 * @throws NullPointerException if obj is <tt>null</tt> 1499 * @return <tt>true</tt> if the current thread holds the monitor lock on 1500 * the specified object. 1501 * @since 1.4 1502 */ 1503 public static native boolean holdsLock(Object obj); 1504 1505 private static final StackTraceElement[] EMPTY_STACK_TRACE 1506 = new StackTraceElement[0]; 1507 1508 /** 1509 * Returns an array of stack trace elements representing the stack dump 1510 * of this thread. This method will return a zero-length array if 1511 * this thread has not started, has started but has not yet been 1512 * scheduled to run by the system, or has terminated. 1513 * If the returned array is of non-zero length then the first element of 1514 * the array represents the top of the stack, which is the most recent 1515 * method invocation in the sequence. The last element of the array 1516 * represents the bottom of the stack, which is the least recent method 1517 * invocation in the sequence. 1518 * 1519 * <p>If there is a security manager, and this thread is not 1520 * the current thread, then the security manager's 1521 * <tt>checkPermission</tt> method is called with a 1522 * <tt>RuntimePermission("getStackTrace")</tt> permission 1523 * to see if it's ok to get the stack trace. 1524 * 1525 * <p>Some virtual machines may, under some circumstances, omit one 1526 * or more stack frames from the stack trace. In the extreme case, 1527 * a virtual machine that has no stack trace information concerning 1528 * this thread is permitted to return a zero-length array from this 1529 * method. 1530 * 1531 * @return an array of <tt>StackTraceElement</tt>, 1532 * each represents one stack frame. 1533 * 1534 * @throws SecurityException 1535 * if a security manager exists and its 1536 * <tt>checkPermission</tt> method doesn't allow 1537 * getting the stack trace of thread. 1538 * @see SecurityManager#checkPermission 1539 * @see RuntimePermission 1540 * @see Throwable#getStackTrace 1541 * 1542 * @since 1.5 1543 */ 1544 public StackTraceElement[] getStackTrace() { 1545 if (this != Thread.currentThread()) { 1546 // check for getStackTrace permission 1547 SecurityManager security = System.getSecurityManager(); 1548 if (security != null) { 1549 security.checkPermission( 1550 SecurityConstants.GET_STACK_TRACE_PERMISSION); 1551 } 1552 // optimization so we do not call into the vm for threads that 1553 // have not yet started or have terminated 1554 if (!isAlive()) { 1555 return EMPTY_STACK_TRACE; 1556 } 1557 StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this}); 1558 StackTraceElement[] stackTrace = stackTraceArray[0]; 1559 // a thread that was alive during the previous isAlive call may have 1560 // since terminated, therefore not having a stacktrace. 1561 if (stackTrace == null) { 1562 stackTrace = EMPTY_STACK_TRACE; 1563 } 1564 return stackTrace; 1565 } else { 1566 // Don't need JVM help for current thread 1567 return (new Exception()).getStackTrace(); 1568 } 1569 } 1570 1571 /** 1572 * Returns a map of stack traces for all live threads. 1573 * The map keys are threads and each map value is an array of 1574 * <tt>StackTraceElement</tt> that represents the stack dump 1575 * of the corresponding <tt>Thread</tt>. 1576 * The returned stack traces are in the format specified for 1577 * the {@link #getStackTrace getStackTrace} method. 1578 * 1579 * <p>The threads may be executing while this method is called. 1580 * The stack trace of each thread only represents a snapshot and 1581 * each stack trace may be obtained at different time. A zero-length 1582 * array will be returned in the map value if the virtual machine has 1583 * no stack trace information about a thread. 1584 * 1585 * <p>If there is a security manager, then the security manager's 1586 * <tt>checkPermission</tt> method is called with a 1587 * <tt>RuntimePermission("getStackTrace")</tt> permission as well as 1588 * <tt>RuntimePermission("modifyThreadGroup")</tt> permission 1589 * to see if it is ok to get the stack trace of all threads. 1590 * 1591 * @return a <tt>Map</tt> from <tt>Thread</tt> to an array of 1592 * <tt>StackTraceElement</tt> that represents the stack trace of 1593 * the corresponding thread. 1594 * 1595 * @throws SecurityException 1596 * if a security manager exists and its 1597 * <tt>checkPermission</tt> method doesn't allow 1598 * getting the stack trace of thread. 1599 * @see #getStackTrace 1600 * @see SecurityManager#checkPermission 1601 * @see RuntimePermission 1602 * @see Throwable#getStackTrace 1603 * 1604 * @since 1.5 1605 */ 1606 public static Map<Thread, StackTraceElement[]> getAllStackTraces() { 1607 // check for getStackTrace permission 1608 SecurityManager security = System.getSecurityManager(); 1609 if (security != null) { 1610 security.checkPermission( 1611 SecurityConstants.GET_STACK_TRACE_PERMISSION); 1612 security.checkPermission( 1613 SecurityConstants.MODIFY_THREADGROUP_PERMISSION); 1614 } 1615 1616 // Get a snapshot of the list of all threads 1617 Thread[] threads = getThreads(); 1618 StackTraceElement[][] traces = dumpThreads(threads); 1619 Map<Thread, StackTraceElement[]> m = new HashMap<>(threads.length); 1620 for (int i = 0; i < threads.length; i++) { 1621 StackTraceElement[] stackTrace = traces[i]; 1622 if (stackTrace != null) { 1623 m.put(threads[i], stackTrace); 1624 } 1625 // else terminated so we don't put it in the map 1626 } 1627 return m; 1628 } 1629 1630 1631 private static final RuntimePermission SUBCLASS_IMPLEMENTATION_PERMISSION = 1632 new RuntimePermission("enableContextClassLoaderOverride"); 1633 1634 /** cache of subclass security audit results */ 1635 /* Replace with ConcurrentReferenceHashMap when/if it appears in a future 1636 * release */ 1637 private static class Caches { 1638 /** cache of subclass security audit results */ 1639 static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits = 1640 new ConcurrentHashMap<>(); 1641 1642 /** queue for WeakReferences to audited subclasses */ 1643 static final ReferenceQueue<Class<?>> subclassAuditsQueue = 1644 new ReferenceQueue<>(); 1645 } 1646 1647 /** 1648 * Verifies that this (possibly subclass) instance can be constructed 1649 * without violating security constraints: the subclass must not override 1650 * security-sensitive non-final methods, or else the 1651 * "enableContextClassLoaderOverride" RuntimePermission is checked. 1652 */ 1653 private static boolean isCCLOverridden(Class cl) { 1654 if (cl == Thread.class) 1655 return false; 1656 1657 processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits); 1658 WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue); 1659 Boolean result = Caches.subclassAudits.get(key); 1660 if (result == null) { 1661 result = Boolean.valueOf(auditSubclass(cl)); 1662 Caches.subclassAudits.putIfAbsent(key, result); 1663 } 1664 1665 return result.booleanValue(); 1666 } 1667 1668 /** 1669 * Performs reflective checks on given subclass to verify that it doesn't 1670 * override security-sensitive non-final methods. Returns true if the 1671 * subclass overrides any of the methods, false otherwise. 1672 */ 1673 private static boolean auditSubclass(final Class subcl) { 1674 Boolean result = AccessController.doPrivileged( 1675 new PrivilegedAction<Boolean>() { 1676 public Boolean run() { 1677 for (Class cl = subcl; 1678 cl != Thread.class; 1679 cl = cl.getSuperclass()) 1680 { 1681 try { 1682 cl.getDeclaredMethod("getContextClassLoader", new Class[0]); 1683 return Boolean.TRUE; 1684 } catch (NoSuchMethodException ex) { 1685 } 1686 try { 1687 Class[] params = {ClassLoader.class}; 1688 cl.getDeclaredMethod("setContextClassLoader", params); 1689 return Boolean.TRUE; 1690 } catch (NoSuchMethodException ex) { 1691 } 1692 } 1693 return Boolean.FALSE; 1694 } 1695 } 1696 ); 1697 return result.booleanValue(); 1698 } 1699 1700 private native static StackTraceElement[][] dumpThreads(Thread[] threads); 1701 private native static Thread[] getThreads(); 1702 1703 /** 1704 * Returns the identifier of this Thread. The thread ID is a positive 1705 * <tt>long</tt> number generated when this thread was created. 1706 * The thread ID is unique and remains unchanged during its lifetime. 1707 * When a thread is terminated, this thread ID may be reused. 1708 * 1709 * @return this thread's ID. 1710 * @since 1.5 1711 */ 1712 public long getId() { 1713 return tid; 1714 } 1715 1716 /** 1717 * A thread state. A thread can be in one of the following states: 1718 * <ul> 1719 * <li>{@link #NEW}<br> 1720 * A thread that has not yet started is in this state. 1721 * </li> 1722 * <li>{@link #RUNNABLE}<br> 1723 * A thread executing in the Java virtual machine is in this state. 1724 * </li> 1725 * <li>{@link #BLOCKED}<br> 1726 * A thread that is blocked waiting for a monitor lock 1727 * is in this state. 1728 * </li> 1729 * <li>{@link #WAITING}<br> 1730 * A thread that is waiting indefinitely for another thread to 1731 * perform a particular action is in this state. 1732 * </li> 1733 * <li>{@link #TIMED_WAITING}<br> 1734 * A thread that is waiting for another thread to perform an action 1735 * for up to a specified waiting time is in this state. 1736 * </li> 1737 * <li>{@link #TERMINATED}<br> 1738 * A thread that has exited is in this state. 1739 * </li> 1740 * </ul> 1741 * 1742 * <p> 1743 * A thread can be in only one state at a given point in time. 1744 * These states are virtual machine states which do not reflect 1745 * any operating system thread states. 1746 * 1747 * @since 1.5 1748 * @see #getState 1749 */ 1750 public enum State { 1751 /** 1752 * Thread state for a thread which has not yet started. 1753 */ 1754 NEW, 1755 1756 /** 1757 * Thread state for a runnable thread. A thread in the runnable 1758 * state is executing in the Java virtual machine but it may 1759 * be waiting for other resources from the operating system 1760 * such as processor. 1761 */ 1762 RUNNABLE, 1763 1764 /** 1765 * Thread state for a thread blocked waiting for a monitor lock. 1766 * A thread in the blocked state is waiting for a monitor lock 1767 * to enter a synchronized block/method or 1768 * reenter a synchronized block/method after calling 1769 * {@link Object#wait() Object.wait}. 1770 */ 1771 BLOCKED, 1772 1773 /** 1774 * Thread state for a waiting thread. 1775 * A thread is in the waiting state due to calling one of the 1776 * following methods: 1777 * <ul> 1778 * <li>{@link Object#wait() Object.wait} with no timeout</li> 1779 * <li>{@link #join() Thread.join} with no timeout</li> 1780 * <li>{@link LockSupport#park() LockSupport.park}</li> 1781 * </ul> 1782 * 1783 * <p>A thread in the waiting state is waiting for another thread to 1784 * perform a particular action. 1785 * 1786 * For example, a thread that has called <tt>Object.wait()</tt> 1787 * on an object is waiting for another thread to call 1788 * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on 1789 * that object. A thread that has called <tt>Thread.join()</tt> 1790 * is waiting for a specified thread to terminate. 1791 */ 1792 WAITING, 1793 1794 /** 1795 * Thread state for a waiting thread with a specified waiting time. 1796 * A thread is in the timed waiting state due to calling one of 1797 * the following methods with a specified positive waiting time: 1798 * <ul> 1799 * <li>{@link #sleep Thread.sleep}</li> 1800 * <li>{@link Object#wait(long) Object.wait} with timeout</li> 1801 * <li>{@link #join(long) Thread.join} with timeout</li> 1802 * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> 1803 * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li> 1804 * </ul> 1805 */ 1806 TIMED_WAITING, 1807 1808 /** 1809 * Thread state for a terminated thread. 1810 * The thread has completed execution. 1811 */ 1812 TERMINATED; 1813 } 1814 1815 /** 1816 * Returns the state of this thread. 1817 * This method is designed for use in monitoring of the system state, 1818 * not for synchronization control. 1819 * 1820 * @return this thread's state. 1821 * @since 1.5 1822 */ 1823 public State getState() { 1824 // get current thread state 1825 return sun.misc.VM.toThreadState(threadStatus); 1826 } 1827 1828 // Added in JSR-166 1829 1830 /** 1831 * Interface for handlers invoked when a <tt>Thread</tt> abruptly 1832 * terminates due to an uncaught exception. 1833 * <p>When a thread is about to terminate due to an uncaught exception 1834 * the Java Virtual Machine will query the thread for its 1835 * <tt>UncaughtExceptionHandler</tt> using 1836 * {@link #getUncaughtExceptionHandler} and will invoke the handler's 1837 * <tt>uncaughtException</tt> method, passing the thread and the 1838 * exception as arguments. 1839 * If a thread has not had its <tt>UncaughtExceptionHandler</tt> 1840 * explicitly set, then its <tt>ThreadGroup</tt> object acts as its 1841 * <tt>UncaughtExceptionHandler</tt>. If the <tt>ThreadGroup</tt> object 1842 * has no 1843 * special requirements for dealing with the exception, it can forward 1844 * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler 1845 * default uncaught exception handler}. 1846 * 1847 * @see #setDefaultUncaughtExceptionHandler 1848 * @see #setUncaughtExceptionHandler 1849 * @see ThreadGroup#uncaughtException 1850 * @since 1.5 1851 */ 1852 public interface UncaughtExceptionHandler { 1853 /** 1854 * Method invoked when the given thread terminates due to the 1855 * given uncaught exception. 1856 * <p>Any exception thrown by this method will be ignored by the 1857 * Java Virtual Machine. 1858 * @param t the thread 1859 * @param e the exception 1860 */ 1861 void uncaughtException(Thread t, Throwable e); 1862 } 1863 1864 // null unless explicitly set 1865 private volatile UncaughtExceptionHandler uncaughtExceptionHandler; 1866 1867 // null unless explicitly set 1868 private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler; 1869 1870 /** 1871 * Set the default handler invoked when a thread abruptly terminates 1872 * due to an uncaught exception, and no other handler has been defined 1873 * for that thread. 1874 * 1875 * <p>Uncaught exception handling is controlled first by the thread, then 1876 * by the thread's {@link ThreadGroup} object and finally by the default 1877 * uncaught exception handler. If the thread does not have an explicit 1878 * uncaught exception handler set, and the thread's thread group 1879 * (including parent thread groups) does not specialize its 1880 * <tt>uncaughtException</tt> method, then the default handler's 1881 * <tt>uncaughtException</tt> method will be invoked. 1882 * <p>By setting the default uncaught exception handler, an application 1883 * can change the way in which uncaught exceptions are handled (such as 1884 * logging to a specific device, or file) for those threads that would 1885 * already accept whatever "default" behavior the system 1886 * provided. 1887 * 1888 * <p>Note that the default uncaught exception handler should not usually 1889 * defer to the thread's <tt>ThreadGroup</tt> object, as that could cause 1890 * infinite recursion. 1891 * 1892 * @param eh the object to use as the default uncaught exception handler. 1893 * If <tt>null</tt> then there is no default handler. 1894 * 1895 * @throws SecurityException if a security manager is present and it 1896 * denies <tt>{@link RuntimePermission} 1897 * ("setDefaultUncaughtExceptionHandler")</tt> 1898 * 1899 * @see #setUncaughtExceptionHandler 1900 * @see #getUncaughtExceptionHandler 1901 * @see ThreadGroup#uncaughtException 1902 * @since 1.5 1903 */ 1904 public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) { 1905 SecurityManager sm = System.getSecurityManager(); 1906 if (sm != null) { 1907 sm.checkPermission( 1908 new RuntimePermission("setDefaultUncaughtExceptionHandler") 1909 ); 1910 } 1911 1912 defaultUncaughtExceptionHandler = eh; 1913 } 1914 1915 /** 1916 * Returns the default handler invoked when a thread abruptly terminates 1917 * due to an uncaught exception. If the returned value is <tt>null</tt>, 1918 * there is no default. 1919 * @since 1.5 1920 * @see #setDefaultUncaughtExceptionHandler 1921 */ 1922 public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){ 1923 return defaultUncaughtExceptionHandler; 1924 } 1925 1926 /** 1927 * Returns the handler invoked when this thread abruptly terminates 1928 * due to an uncaught exception. If this thread has not had an 1929 * uncaught exception handler explicitly set then this thread's 1930 * <tt>ThreadGroup</tt> object is returned, unless this thread 1931 * has terminated, in which case <tt>null</tt> is returned. 1932 * @since 1.5 1933 */ 1934 public UncaughtExceptionHandler getUncaughtExceptionHandler() { 1935 return uncaughtExceptionHandler != null ? 1936 uncaughtExceptionHandler : group; 1937 } 1938 1939 /** 1940 * Set the handler invoked when this thread abruptly terminates 1941 * due to an uncaught exception. 1942 * <p>A thread can take full control of how it responds to uncaught 1943 * exceptions by having its uncaught exception handler explicitly set. 1944 * If no such handler is set then the thread's <tt>ThreadGroup</tt> 1945 * object acts as its handler. 1946 * @param eh the object to use as this thread's uncaught exception 1947 * handler. If <tt>null</tt> then this thread has no explicit handler. 1948 * @throws SecurityException if the current thread is not allowed to 1949 * modify this thread. 1950 * @see #setDefaultUncaughtExceptionHandler 1951 * @see ThreadGroup#uncaughtException 1952 * @since 1.5 1953 */ 1954 public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) { 1955 checkAccess(); 1956 uncaughtExceptionHandler = eh; 1957 } 1958 1959 /** 1960 * Dispatch an uncaught exception to the handler. This method is 1961 * intended to be called only by the JVM. 1962 */ 1963 private void dispatchUncaughtException(Throwable e) { 1964 getUncaughtExceptionHandler().uncaughtException(this, e); 1965 } 1966 1967 /** 1968 * Removes from the specified map any keys that have been enqueued 1969 * on the specified reference queue. 1970 */ 1971 static void processQueue(ReferenceQueue<Class<?>> queue, 1972 ConcurrentMap<? extends 1973 WeakReference<Class<?>>, ?> map) 1974 { 1975 Reference<? extends Class<?>> ref; 1976 while((ref = queue.poll()) != null) { 1977 map.remove(ref); 1978 } 1979 } 1980 1981 /** 1982 * Weak key for Class objects. 1983 **/ 1984 static class WeakClassKey extends WeakReference<Class<?>> { 1985 /** 1986 * saved value of the referent's identity hash code, to maintain 1987 * a consistent hash code after the referent has been cleared 1988 */ 1989 private final int hash; 1990 1991 /** 1992 * Create a new WeakClassKey to the given object, registered 1993 * with a queue. 1994 */ 1995 WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) { 1996 super(cl, refQueue); 1997 hash = System.identityHashCode(cl); 1998 } 1999 2000 /** 2001 * Returns the identity hash code of the original referent. 2002 */ 2003 @Override 2004 public int hashCode() { 2005 return hash; 2006 } 2007 2008 /** 2009 * Returns true if the given object is this identical 2010 * WeakClassKey instance, or, if this object's referent has not 2011 * been cleared, if the given object is another WeakClassKey 2012 * instance with the identical non-null referent as this one. 2013 */ 2014 @Override 2015 public boolean equals(Object obj) { 2016 if (obj == this) 2017 return true; 2018 2019 if (obj instanceof WeakClassKey) { 2020 Object referent = get(); 2021 return (referent != null) && 2022 (referent == ((WeakClassKey) obj).get()); 2023 } else { 2024 return false; 2025 } 2026 } 2027 } 2028 2029 /* Some private helper methods */ 2030 private native void setPriority0(int newPriority); 2031 private native void stop0(Object o); 2032 private native void suspend0(); 2033 private native void resume0(); 2034 private native void interrupt0(); 2035 }