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