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