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