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