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