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