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