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