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