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