1 /*
   2  * Copyright (c) 1994, 2019, 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 sun.nio.ch.Interruptible;
  43 import jdk.internal.reflect.CallerSensitive;
  44 import jdk.internal.reflect.Reflection;
  45 import sun.security.util.SecurityConstants;
  46 import jdk.internal.HotSpotIntrinsicCandidate;
  47 
  48 /**
  49  * A <i>thread</i> is a thread of execution in a program. The Java
  50  * Virtual Machine allows an application to have multiple threads of
  51  * execution running concurrently.
  52  * <p>
  53  * Every thread has a priority. Threads with higher priority are
  54  * executed in preference to threads with lower priority. Each thread
  55  * may or may not also be marked as a daemon. When code running in
  56  * some thread creates a new {@code Thread} object, the new
  57  * thread has its priority initially set equal to the priority of the
  58  * creating thread, and is a daemon thread if and only if the
  59  * creating thread is a daemon.
  60  * <p>
  61  * When a Java Virtual Machine starts up, there is usually a single
  62  * non-daemon thread (which typically calls the method named
  63  * {@code main} of some designated class). The Java Virtual
  64  * Machine continues to execute threads until either of the following
  65  * occurs:
  66  * <ul>
  67  * <li>The {@code exit} method of class {@code Runtime} has been
  68  *     called and the security manager has permitted the exit operation
  69  *     to take place.
  70  * <li>All threads that are not daemon threads have died, either by
  71  *     returning from the call to the {@code run} method or by
  72  *     throwing an exception that propagates beyond the {@code run}
  73  *     method.
  74  * </ul>
  75  * <p>
  76  * There are two ways to create a new thread of execution. One is to
  77  * declare a class to be a subclass of {@code Thread}. This
  78  * subclass should override the {@code run} method of class
  79  * {@code Thread}. An instance of the subclass can then be
  80  * allocated and started. For example, a thread that computes primes
  81  * larger than a stated value could be written as follows:
  82  * <hr><blockquote><pre>
  83  *     class PrimeThread extends Thread {
  84  *         long minPrime;
  85  *         PrimeThread(long minPrime) {
  86  *             this.minPrime = minPrime;
  87  *         }
  88  *
  89  *         public void run() {
  90  *             // compute primes larger than minPrime
  91  *             &nbsp;.&nbsp;.&nbsp;.
  92  *         }
  93  *     }
  94  * </pre></blockquote><hr>
  95  * <p>
  96  * The following code would then create a thread and start it running:
  97  * <blockquote><pre>
  98  *     PrimeThread p = new PrimeThread(143);
  99  *     p.start();
 100  * </pre></blockquote>
 101  * <p>
 102  * The other way to create a thread is to declare a class that
 103  * implements the {@code Runnable} interface. That class then
 104  * implements the {@code run} method. An instance of the class can
 105  * then be allocated, passed as an argument when creating
 106  * {@code Thread}, and started. The same example in this other
 107  * style looks like the following:
 108  * <hr><blockquote><pre>
 109  *     class PrimeRun implements Runnable {
 110  *         long minPrime;
 111  *         PrimeRun(long minPrime) {
 112  *             this.minPrime = minPrime;
 113  *         }
 114  *
 115  *         public void run() {
 116  *             // compute primes larger than minPrime
 117  *             &nbsp;.&nbsp;.&nbsp;.
 118  *         }
 119  *     }
 120  * </pre></blockquote><hr>
 121  * <p>
 122  * The following code would then create a thread and start it running:
 123  * <blockquote><pre>
 124  *     PrimeRun p = new PrimeRun(143);
 125  *     new Thread(p).start();
 126  * </pre></blockquote>
 127  * <p>
 128  * Every thread has a name for identification purposes. More than
 129  * one thread may have the same name. If a name is not specified when
 130  * a thread is created, a new name is generated for it.
 131  * <p>
 132  * Unless otherwise noted, passing a {@code null} argument to a constructor
 133  * or method in this class will cause a {@link NullPointerException} to be
 134  * thrown.
 135  *
 136  * @author  unascribed
 137  * @see     Runnable
 138  * @see     Runtime#exit(int)
 139  * @see     #run()
 140  * @see     #stop()
 141  * @since   1.0
 142  */
 143 public
 144 class Thread implements Runnable {
 145     /* Make sure registerNatives is the first thing <clinit> does. */
 146     private static native void registerNatives();
 147     static {
 148         registerNatives();
 149     }
 150 
 151     private volatile String name;
 152     private int priority;
 153 
 154     /* Whether or not the thread is a daemon thread. */
 155     private boolean daemon = false;
 156 
 157     /* Fields reserved for exclusive use by the JVM */
 158     private boolean stillborn = false;
 159     private long eetop;
 160 
 161     /* What will be run. */
 162     private Runnable target;
 163 
 164     /* The group of this thread */
 165     private ThreadGroup group;
 166 
 167     /* The context ClassLoader for this thread */
 168     private ClassLoader contextClassLoader;
 169 
 170     /* The inherited AccessControlContext of this thread */
 171     private AccessControlContext inheritedAccessControlContext;
 172 
 173     /* For autonumbering anonymous threads. */
 174     private static int threadInitNumber;
 175     private static synchronized int nextThreadNum() {
 176         return threadInitNumber++;
 177     }
 178 
 179     /* ThreadLocal values pertaining to this thread. This map is maintained
 180      * by the ThreadLocal class. */
 181     ThreadLocal.ThreadLocalMap threadLocals = null;
 182 
 183     /*
 184      * InheritableThreadLocal values pertaining to this thread. This map is
 185      * maintained by the InheritableThreadLocal class.
 186      */
 187     ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
 188 
 189     /*
 190      * The requested stack size for this thread, or 0 if the creator did
 191      * not specify a stack size.  It is up to the VM to do whatever it
 192      * likes with this number; some VMs will ignore it.
 193      */
 194     private final long stackSize;
 195 
 196     /*
 197      * JVM-private state that persists after native thread termination.
 198      */
 199     private long nativeParkEventPointer;
 200 
 201     /*
 202      * Thread ID
 203      */
 204     private final long tid;
 205 
 206     /* For generating thread ID */
 207     private static long threadSeqNumber;
 208 
 209     private static synchronized long nextThreadID() {
 210         return ++threadSeqNumber;
 211     }
 212 
 213     /*
 214      * Java thread status for tools, default indicates thread 'not yet started'
 215      */
 216     private volatile int threadStatus;
 217 
 218     /**
 219      * The argument supplied to the current call to
 220      * java.util.concurrent.locks.LockSupport.park.
 221      * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
 222      * Accessed using java.util.concurrent.locks.LockSupport.getBlocker
 223      */
 224     volatile Object parkBlocker;
 225 
 226     /* The object in which this thread is blocked in an interruptible I/O
 227      * operation, if any.  The blocker's interrupt method should be invoked
 228      * after setting this thread's interrupt status.
 229      */
 230     private volatile Interruptible blocker;
 231     private final Object blockerLock = new Object();
 232 
 233     /* Set the blocker field; invoked via jdk.internal.access.SharedSecrets
 234      * from java.nio code
 235      */
 236     static void blockedOn(Interruptible b) {
 237         Thread me = Thread.currentThread();
 238         synchronized (me.blockerLock) {
 239             me.blocker = b;
 240         }
 241     }
 242 
 243     /**
 244      * The minimum priority that a thread can have.
 245      */
 246     public static final int MIN_PRIORITY = 1;
 247 
 248    /**
 249      * The default priority that is assigned to a thread.
 250      */
 251     public static final int NORM_PRIORITY = 5;
 252 
 253     /**
 254      * The maximum priority that a thread can have.
 255      */
 256     public static final int MAX_PRIORITY = 10;
 257 
 258     /**
 259      * Returns a reference to the currently executing thread object.
 260      *
 261      * @return  the currently executing thread.
 262      */
 263     @HotSpotIntrinsicCandidate
 264     public static native Thread currentThread();
 265 
 266     /**
 267      * A hint to the scheduler that the current thread is willing to yield
 268      * its current use of a processor. The scheduler is free to ignore this
 269      * hint.
 270      *
 271      * <p> Yield is a heuristic attempt to improve relative progression
 272      * between threads that would otherwise over-utilise a CPU. Its use
 273      * should be combined with detailed profiling and benchmarking to
 274      * ensure that it actually has the desired effect.
 275      *
 276      * <p> It is rarely appropriate to use this method. It may be useful
 277      * for debugging or testing purposes, where it may help to reproduce
 278      * bugs due to race conditions. It may also be useful when designing
 279      * concurrency control constructs such as the ones in the
 280      * {@link java.util.concurrent.locks} package.
 281      */
 282     public static native void yield();
 283 
 284     /**
 285      * Causes the currently executing thread to sleep (temporarily cease
 286      * execution) for the specified number of milliseconds, subject to
 287      * the precision and accuracy of system timers and schedulers. The thread
 288      * does not lose ownership of any monitors.
 289      *
 290      * @param  millis
 291      *         the length of time to sleep in milliseconds
 292      *
 293      * @throws  IllegalArgumentException
 294      *          if the value of {@code millis} is negative
 295      *
 296      * @throws  InterruptedException
 297      *          if any thread has interrupted the current thread. The
 298      *          <i>interrupted status</i> of the current thread is
 299      *          cleared when this exception is thrown.
 300      */
 301     public static native void sleep(long millis) throws InterruptedException;
 302 
 303     /**
 304      * Causes the currently executing thread to sleep (temporarily cease
 305      * execution) for the specified number of milliseconds plus the specified
 306      * number of nanoseconds, subject to the precision and accuracy of system
 307      * timers and schedulers. The thread does not lose ownership of any
 308      * monitors.
 309      *
 310      * @param  millis
 311      *         the length of time to sleep in milliseconds
 312      *
 313      * @param  nanos
 314      *         {@code 0-999999} additional nanoseconds to sleep
 315      *
 316      * @throws  IllegalArgumentException
 317      *          if the value of {@code millis} is negative, or the value of
 318      *          {@code nanos} is not in the range {@code 0-999999}
 319      *
 320      * @throws  InterruptedException
 321      *          if any thread has interrupted the current thread. The
 322      *          <i>interrupted status</i> of the current thread is
 323      *          cleared when this exception is thrown.
 324      */
 325     public static void sleep(long millis, int nanos)
 326     throws InterruptedException {
 327         if (millis < 0) {
 328             throw new IllegalArgumentException("timeout value is negative");
 329         }
 330 
 331         if (nanos < 0 || nanos > 999999) {
 332             throw new IllegalArgumentException(
 333                                 "nanosecond timeout value out of range");
 334         }
 335 
 336         if (nanos > 0 && millis < Long.MAX_VALUE) {
 337             millis++;
 338         }
 339 
 340         sleep(millis);
 341     }
 342 
 343     /**
 344      * Indicates that the caller is momentarily unable to progress, until the
 345      * occurrence of one or more actions on the part of other activities. By
 346      * invoking this method within each iteration of a spin-wait loop construct,
 347      * the calling thread indicates to the runtime that it is busy-waiting.
 348      * The runtime may take action to improve the performance of invoking
 349      * spin-wait loop constructions.
 350      *
 351      * @apiNote
 352      * As an example consider a method in a class that spins in a loop until
 353      * some flag is set outside of that method. A call to the {@code onSpinWait}
 354      * method should be placed inside the spin loop.
 355      * <pre>{@code
 356      *     class EventHandler {
 357      *         volatile boolean eventNotificationNotReceived;
 358      *         void waitForEventAndHandleIt() {
 359      *             while ( eventNotificationNotReceived ) {
 360      *                 java.lang.Thread.onSpinWait();
 361      *             }
 362      *             readAndProcessEvent();
 363      *         }
 364      *
 365      *         void readAndProcessEvent() {
 366      *             // Read event from some source and process it
 367      *              . . .
 368      *         }
 369      *     }
 370      * }</pre>
 371      * <p>
 372      * The code above would remain correct even if the {@code onSpinWait}
 373      * method was not called at all. However on some architectures the Java
 374      * Virtual Machine may issue the processor instructions to address such
 375      * code patterns in a more beneficial way.
 376      *
 377      * @since 9
 378      */
 379     @HotSpotIntrinsicCandidate
 380     public static void onSpinWait() {}
 381 
 382     /**
 383      * Initializes a Thread.
 384      *
 385      * @param g the Thread group
 386      * @param target the object whose run() method gets called
 387      * @param name the name of the new Thread
 388      * @param stackSize the desired stack size for the new thread, or
 389      *        zero to indicate that this parameter is to be ignored.
 390      * @param acc the AccessControlContext to inherit, or
 391      *            AccessController.getContext() if null
 392      * @param inheritThreadLocals if {@code true}, inherit initial values for
 393      *            inheritable thread-locals from the constructing thread
 394      */
 395     private Thread(ThreadGroup g, Runnable target, String name,
 396                    long stackSize, AccessControlContext acc,
 397                    boolean inheritThreadLocals) {
 398         if (name == null) {
 399             throw new NullPointerException("name cannot be null");
 400         }
 401 
 402         this.name = name;
 403 
 404         Thread parent = currentThread();
 405         SecurityManager security = System.getSecurityManager();
 406         if (g == null) {
 407             /* Determine if it's an applet or not */
 408 
 409             /* If there is a security manager, ask the security manager
 410                what to do. */
 411             if (security != null) {
 412                 g = security.getThreadGroup();
 413             }
 414 
 415             /* If the security manager doesn't have a strong opinion
 416                on the matter, use the parent thread group. */
 417             if (g == null) {
 418                 g = parent.getThreadGroup();
 419             }
 420         }
 421 
 422         /* checkAccess regardless of whether or not threadgroup is
 423            explicitly passed in. */
 424         g.checkAccess();
 425 
 426         /*
 427          * Do we have the required permissions?
 428          */
 429         if (security != null) {
 430             if (isCCLOverridden(getClass())) {
 431                 security.checkPermission(
 432                         SecurityConstants.SUBCLASS_IMPLEMENTATION_PERMISSION);
 433             }
 434         }
 435 
 436         g.addUnstarted();
 437 
 438         this.group = g;
 439         this.daemon = parent.isDaemon();
 440         this.priority = parent.getPriority();
 441         if (security == null || isCCLOverridden(parent.getClass()))
 442             this.contextClassLoader = parent.getContextClassLoader();
 443         else
 444             this.contextClassLoader = parent.contextClassLoader;
 445         this.inheritedAccessControlContext =
 446                 acc != null ? acc : AccessController.getContext();
 447         this.target = target;
 448         setPriority(priority);
 449         if (inheritThreadLocals && parent.inheritableThreadLocals != null)
 450             this.inheritableThreadLocals =
 451                 ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
 452         /* Stash the specified stack size in case the VM cares */
 453         this.stackSize = stackSize;
 454 
 455         /* Set thread ID */
 456         this.tid = nextThreadID();
 457     }
 458 
 459     /**
 460      * Throws CloneNotSupportedException as a Thread can not be meaningfully
 461      * cloned. Construct a new Thread instead.
 462      *
 463      * @throws  CloneNotSupportedException
 464      *          always
 465      */
 466     @Override
 467     protected Object clone() throws CloneNotSupportedException {
 468         throw new CloneNotSupportedException();
 469     }
 470 
 471     /**
 472      * Allocates a new {@code Thread} object. This constructor has the same
 473      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
 474      * {@code (null, null, gname)}, where {@code gname} is a newly generated
 475      * name. Automatically generated names are of the form
 476      * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
 477      */
 478     public Thread() {
 479         this(null, null, "Thread-" + nextThreadNum(), 0);
 480     }
 481 
 482     /**
 483      * Allocates a new {@code Thread} object. This constructor has the same
 484      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
 485      * {@code (null, target, gname)}, where {@code gname} is a newly generated
 486      * name. Automatically generated names are of the form
 487      * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
 488      *
 489      * @param  target
 490      *         the object whose {@code run} method is invoked when this thread
 491      *         is started. If {@code null}, this classes {@code run} method does
 492      *         nothing.
 493      */
 494     public Thread(Runnable target) {
 495         this(null, target, "Thread-" + nextThreadNum(), 0);
 496     }
 497 
 498     /**
 499      * Creates a new Thread that inherits the given AccessControlContext
 500      * but thread-local variables are not inherited.
 501      * This is not a public constructor.
 502      */
 503     Thread(Runnable target, AccessControlContext acc) {
 504         this(null, target, "Thread-" + nextThreadNum(), 0, acc, false);
 505     }
 506 
 507     /**
 508      * Allocates a new {@code Thread} object. This constructor has the same
 509      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
 510      * {@code (group, target, gname)} ,where {@code gname} is a newly generated
 511      * name. Automatically generated names are of the form
 512      * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
 513      *
 514      * @param  group
 515      *         the thread group. If {@code null} and there is a security
 516      *         manager, the group is determined by {@linkplain
 517      *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
 518      *         If there is not a security manager or {@code
 519      *         SecurityManager.getThreadGroup()} returns {@code null}, the group
 520      *         is set to the current thread's thread group.
 521      *
 522      * @param  target
 523      *         the object whose {@code run} method is invoked when this thread
 524      *         is started. If {@code null}, this thread's run method is invoked.
 525      *
 526      * @throws  SecurityException
 527      *          if the current thread cannot create a thread in the specified
 528      *          thread group
 529      */
 530     public Thread(ThreadGroup group, Runnable target) {
 531         this(group, target, "Thread-" + nextThreadNum(), 0);
 532     }
 533 
 534     /**
 535      * Allocates a new {@code Thread} object. This constructor has the same
 536      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
 537      * {@code (null, null, name)}.
 538      *
 539      * @param   name
 540      *          the name of the new thread
 541      */
 542     public Thread(String name) {
 543         this(null, null, name, 0);
 544     }
 545 
 546     /**
 547      * Allocates a new {@code Thread} object. This constructor has the same
 548      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
 549      * {@code (group, null, name)}.
 550      *
 551      * @param  group
 552      *         the thread group. If {@code null} and there is a security
 553      *         manager, the group is determined by {@linkplain
 554      *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
 555      *         If there is not a security manager or {@code
 556      *         SecurityManager.getThreadGroup()} returns {@code null}, the group
 557      *         is set to the current thread's thread group.
 558      *
 559      * @param  name
 560      *         the name of the new thread
 561      *
 562      * @throws  SecurityException
 563      *          if the current thread cannot create a thread in the specified
 564      *          thread group
 565      */
 566     public Thread(ThreadGroup group, String name) {
 567         this(group, null, name, 0);
 568     }
 569 
 570     /**
 571      * Allocates a new {@code Thread} object. This constructor has the same
 572      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
 573      * {@code (null, target, name)}.
 574      *
 575      * @param  target
 576      *         the object whose {@code run} method is invoked when this thread
 577      *         is started. If {@code null}, this thread's run method is invoked.
 578      *
 579      * @param  name
 580      *         the name of the new thread
 581      */
 582     public Thread(Runnable target, String name) {
 583         this(null, target, name, 0);
 584     }
 585 
 586     /**
 587      * Allocates a new {@code Thread} object so that it has {@code target}
 588      * as its run object, has the specified {@code name} as its name,
 589      * and belongs to the thread group referred to by {@code group}.
 590      *
 591      * <p>If there is a security manager, its
 592      * {@link SecurityManager#checkAccess(ThreadGroup) checkAccess}
 593      * method is invoked with the ThreadGroup as its argument.
 594      *
 595      * <p>In addition, its {@code checkPermission} method is invoked with
 596      * the {@code RuntimePermission("enableContextClassLoaderOverride")}
 597      * permission when invoked directly or indirectly by the constructor
 598      * of a subclass which overrides the {@code getContextClassLoader}
 599      * or {@code setContextClassLoader} methods.
 600      *
 601      * <p>The priority of the newly created thread is set equal to the
 602      * priority of the thread creating it, that is, the currently running
 603      * thread. The method {@linkplain #setPriority setPriority} may be
 604      * used to change the priority to a new value.
 605      *
 606      * <p>The newly created thread is initially marked as being a daemon
 607      * thread if and only if the thread creating it is currently marked
 608      * as a daemon thread. The method {@linkplain #setDaemon setDaemon}
 609      * may be used to change whether or not a thread is a daemon.
 610      *
 611      * @param  group
 612      *         the thread group. If {@code null} and there is a security
 613      *         manager, the group is determined by {@linkplain
 614      *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
 615      *         If there is not a security manager or {@code
 616      *         SecurityManager.getThreadGroup()} returns {@code null}, the group
 617      *         is set to the current thread's thread group.
 618      *
 619      * @param  target
 620      *         the object whose {@code run} method is invoked when this thread
 621      *         is started. If {@code null}, this thread's run method is invoked.
 622      *
 623      * @param  name
 624      *         the name of the new thread
 625      *
 626      * @throws  SecurityException
 627      *          if the current thread cannot create a thread in the specified
 628      *          thread group or cannot override the context class loader methods.
 629      */
 630     public Thread(ThreadGroup group, Runnable target, String name) {
 631         this(group, target, name, 0);
 632     }
 633 
 634     /**
 635      * Allocates a new {@code Thread} object so that it has {@code target}
 636      * as its run object, has the specified {@code name} as its name,
 637      * and belongs to the thread group referred to by {@code group}, and has
 638      * the specified <i>stack size</i>.
 639      *
 640      * <p>This constructor is identical to {@link
 641      * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact
 642      * that it allows the thread stack size to be specified.  The stack size
 643      * is the approximate number of bytes of address space that the virtual
 644      * machine is to allocate for this thread's stack.  <b>The effect of the
 645      * {@code stackSize} parameter, if any, is highly platform dependent.</b>
 646      *
 647      * <p>On some platforms, specifying a higher value for the
 648      * {@code stackSize} parameter may allow a thread to achieve greater
 649      * recursion depth before throwing a {@link StackOverflowError}.
 650      * Similarly, specifying a lower value may allow a greater number of
 651      * threads to exist concurrently without throwing an {@link
 652      * OutOfMemoryError} (or other internal error).  The details of
 653      * the relationship between the value of the {@code stackSize} parameter
 654      * and the maximum recursion depth and concurrency level are
 655      * platform-dependent.  <b>On some platforms, the value of the
 656      * {@code stackSize} parameter may have no effect whatsoever.</b>
 657      *
 658      * <p>The virtual machine is free to treat the {@code stackSize}
 659      * parameter as a suggestion.  If the specified value is unreasonably low
 660      * for the platform, the virtual machine may instead use some
 661      * platform-specific minimum value; if the specified value is unreasonably
 662      * high, the virtual machine may instead use some platform-specific
 663      * maximum.  Likewise, the virtual machine is free to round the specified
 664      * value up or down as it sees fit (or to ignore it completely).
 665      *
 666      * <p>Specifying a value of zero for the {@code stackSize} parameter will
 667      * cause this constructor to behave exactly like the
 668      * {@code Thread(ThreadGroup, Runnable, String)} constructor.
 669      *
 670      * <p><i>Due to the platform-dependent nature of the behavior of this
 671      * constructor, extreme care should be exercised in its use.
 672      * The thread stack size necessary to perform a given computation will
 673      * likely vary from one JRE implementation to another.  In light of this
 674      * variation, careful tuning of the stack size parameter may be required,
 675      * and the tuning may need to be repeated for each JRE implementation on
 676      * which an application is to run.</i>
 677      *
 678      * <p>Implementation note: Java platform implementers are encouraged to
 679      * document their implementation's behavior with respect to the
 680      * {@code stackSize} parameter.
 681      *
 682      *
 683      * @param  group
 684      *         the thread group. If {@code null} and there is a security
 685      *         manager, the group is determined by {@linkplain
 686      *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
 687      *         If there is not a security manager or {@code
 688      *         SecurityManager.getThreadGroup()} returns {@code null}, the group
 689      *         is set to the current thread's thread group.
 690      *
 691      * @param  target
 692      *         the object whose {@code run} method is invoked when this thread
 693      *         is started. If {@code null}, this thread's run method is invoked.
 694      *
 695      * @param  name
 696      *         the name of the new thread
 697      *
 698      * @param  stackSize
 699      *         the desired stack size for the new thread, or zero to indicate
 700      *         that this parameter is to be ignored.
 701      *
 702      * @throws  SecurityException
 703      *          if the current thread cannot create a thread in the specified
 704      *          thread group
 705      *
 706      * @since 1.4
 707      */
 708     public Thread(ThreadGroup group, Runnable target, String name,
 709                   long stackSize) {
 710         this(group, target, name, stackSize, null, true);
 711     }
 712 
 713     /**
 714      * Allocates a new {@code Thread} object so that it has {@code target}
 715      * as its run object, has the specified {@code name} as its name,
 716      * belongs to the thread group referred to by {@code group}, has
 717      * the specified {@code stackSize}, and inherits initial values for
 718      * {@linkplain InheritableThreadLocal inheritable thread-local} variables
 719      * if {@code inheritThreadLocals} is {@code true}.
 720      *
 721      * <p> This constructor is identical to {@link
 722      * #Thread(ThreadGroup,Runnable,String,long)} with the added ability to
 723      * suppress, or not, the inheriting of initial values for inheritable
 724      * thread-local variables from the constructing thread. This allows for
 725      * finer grain control over inheritable thread-locals. Care must be taken
 726      * when passing a value of {@code false} for {@code inheritThreadLocals},
 727      * as it may lead to unexpected behavior if the new thread executes code
 728      * that expects a specific thread-local value to be inherited.
 729      *
 730      * <p> Specifying a value of {@code true} for the {@code inheritThreadLocals}
 731      * parameter will cause this constructor to behave exactly like the
 732      * {@code Thread(ThreadGroup, Runnable, String, long)} constructor.
 733      *
 734      * @param  group
 735      *         the thread group. If {@code null} and there is a security
 736      *         manager, the group is determined by {@linkplain
 737      *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
 738      *         If there is not a security manager or {@code
 739      *         SecurityManager.getThreadGroup()} returns {@code null}, the group
 740      *         is set to the current thread's thread group.
 741      *
 742      * @param  target
 743      *         the object whose {@code run} method is invoked when this thread
 744      *         is started. If {@code null}, this thread's run method is invoked.
 745      *
 746      * @param  name
 747      *         the name of the new thread
 748      *
 749      * @param  stackSize
 750      *         the desired stack size for the new thread, or zero to indicate
 751      *         that this parameter is to be ignored
 752      *
 753      * @param  inheritThreadLocals
 754      *         if {@code true}, inherit initial values for inheritable
 755      *         thread-locals from the constructing thread, otherwise no initial
 756      *         values are inherited
 757      *
 758      * @throws  SecurityException
 759      *          if the current thread cannot create a thread in the specified
 760      *          thread group
 761      *
 762      * @since 9
 763      */
 764     public Thread(ThreadGroup group, Runnable target, String name,
 765                   long stackSize, boolean inheritThreadLocals) {
 766         this(group, target, name, stackSize, null, inheritThreadLocals);
 767     }
 768 
 769     /**
 770      * Causes this thread to begin execution; the Java Virtual Machine
 771      * calls the {@code run} method of this thread.
 772      * <p>
 773      * The result is that two threads are running concurrently: the
 774      * current thread (which returns from the call to the
 775      * {@code start} method) and the other thread (which executes its
 776      * {@code run} method).
 777      * <p>
 778      * It is never legal to start a thread more than once.
 779      * In particular, a thread may not be restarted once it has completed
 780      * execution.
 781      *
 782      * @throws     IllegalThreadStateException  if the thread was already started.
 783      * @see        #run()
 784      * @see        #stop()
 785      */
 786     public synchronized void start() {
 787         /**
 788          * This method is not invoked for the main method thread or "system"
 789          * group threads created/set up by the VM. Any new functionality added
 790          * to this method in the future may have to also be added to the VM.
 791          *
 792          * A zero status value corresponds to state "NEW".
 793          */
 794         if (threadStatus != 0)
 795             throw new IllegalThreadStateException();
 796 
 797         /* Notify the group that this thread is about to be started
 798          * so that it can be added to the group's list of threads
 799          * and the group's unstarted count can be decremented. */
 800         group.add(this);
 801 
 802         boolean started = false;
 803         try {
 804             start0();
 805             started = true;
 806         } finally {
 807             try {
 808                 if (!started) {
 809                     group.threadStartFailed(this);
 810                 }
 811             } catch (Throwable ignore) {
 812                 /* do nothing. If start0 threw a Throwable then
 813                   it will be passed up the call stack */
 814             }
 815         }
 816     }
 817 
 818     private native void start0();
 819 
 820     /**
 821      * If this thread was constructed using a separate
 822      * {@code Runnable} run object, then that
 823      * {@code Runnable} object's {@code run} method is called;
 824      * otherwise, this method does nothing and returns.
 825      * <p>
 826      * Subclasses of {@code Thread} should override this method.
 827      *
 828      * @see     #start()
 829      * @see     #stop()
 830      * @see     #Thread(ThreadGroup, Runnable, String)
 831      */
 832     @Override
 833     public void run() {
 834         if (target != null) {
 835             target.run();
 836         }
 837     }
 838 
 839     /**
 840      * This method is called by the system to give a Thread
 841      * a chance to clean up before it actually exits.
 842      */
 843     private void exit() {
 844         if (threadLocals != null && TerminatingThreadLocal.REGISTRY.isPresent()) {
 845             TerminatingThreadLocal.threadTerminated();
 846         }
 847         if (group != null) {
 848             group.threadTerminated(this);
 849             group = null;
 850         }
 851         /* Aggressively null out all reference fields: see bug 4006245 */
 852         target = null;
 853         /* Speed the release of some of these resources */
 854         threadLocals = null;
 855         inheritableThreadLocals = null;
 856         inheritedAccessControlContext = null;
 857         blocker = null;
 858         uncaughtExceptionHandler = null;
 859     }
 860 
 861     /**
 862      * Forces the thread to stop executing.
 863      * <p>
 864      * If there is a security manager installed, its {@code checkAccess}
 865      * method is called with {@code this}
 866      * as its argument. This may result in a
 867      * {@code SecurityException} being raised (in the current thread).
 868      * <p>
 869      * If this thread is different from the current thread (that is, the current
 870      * thread is trying to stop a thread other than itself), the
 871      * security manager's {@code checkPermission} method (with a
 872      * {@code RuntimePermission("stopThread")} argument) is called in
 873      * addition.
 874      * Again, this may result in throwing a
 875      * {@code SecurityException} (in the current thread).
 876      * <p>
 877      * The thread represented by this thread is forced to stop whatever
 878      * it is doing abnormally and to throw a newly created
 879      * {@code ThreadDeath} object as an exception.
 880      * <p>
 881      * It is permitted to stop a thread that has not yet been started.
 882      * If the thread is eventually started, it immediately terminates.
 883      * <p>
 884      * An application should not normally try to catch
 885      * {@code ThreadDeath} unless it must do some extraordinary
 886      * cleanup operation (note that the throwing of
 887      * {@code ThreadDeath} causes {@code finally} clauses of
 888      * {@code try} statements to be executed before the thread
 889      * officially dies).  If a {@code catch} clause catches a
 890      * {@code ThreadDeath} object, it is important to rethrow the
 891      * object so that the thread actually dies.
 892      * <p>
 893      * The top-level error handler that reacts to otherwise uncaught
 894      * exceptions does not print out a message or otherwise notify the
 895      * application if the uncaught exception is an instance of
 896      * {@code ThreadDeath}.
 897      *
 898      * @throws     SecurityException  if the current thread cannot
 899      *             modify this thread.
 900      * @see        #interrupt()
 901      * @see        #checkAccess()
 902      * @see        #run()
 903      * @see        #start()
 904      * @see        ThreadDeath
 905      * @see        ThreadGroup#uncaughtException(Thread,Throwable)
 906      * @see        SecurityManager#checkAccess(Thread)
 907      * @see        SecurityManager#checkPermission
 908      * @deprecated This method is inherently unsafe.  Stopping a thread with
 909      *       Thread.stop causes it to unlock all of the monitors that it
 910      *       has locked (as a natural consequence of the unchecked
 911      *       {@code ThreadDeath} exception propagating up the stack).  If
 912      *       any of the objects previously protected by these monitors were in
 913      *       an inconsistent state, the damaged objects become visible to
 914      *       other threads, potentially resulting in arbitrary behavior.  Many
 915      *       uses of {@code stop} should be replaced by code that simply
 916      *       modifies some variable to indicate that the target thread should
 917      *       stop running.  The target thread should check this variable
 918      *       regularly, and return from its run method in an orderly fashion
 919      *       if the variable indicates that it is to stop running.  If the
 920      *       target thread waits for long periods (on a condition variable,
 921      *       for example), the {@code interrupt} method should be used to
 922      *       interrupt the wait.
 923      *       For more information, see
 924      *       <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
 925      *       are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
 926      */
 927     @Deprecated(since="1.2")
 928     public final void stop() {
 929         SecurityManager security = System.getSecurityManager();
 930         if (security != null) {
 931             checkAccess();
 932             if (this != Thread.currentThread()) {
 933                 security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
 934             }
 935         }
 936         // A zero status value corresponds to "NEW", it can't change to
 937         // not-NEW because we hold the lock.
 938         if (threadStatus != 0) {
 939             resume(); // Wake up thread if it was suspended; no-op otherwise
 940         }
 941 
 942         // The VM can handle all thread states
 943         stop0(new ThreadDeath());
 944     }
 945 
 946     /**
 947      * Interrupts this thread.
 948      *
 949      * <p> Unless the current thread is interrupting itself, which is
 950      * always permitted, the {@link #checkAccess() checkAccess} method
 951      * of this thread is invoked, which may cause a {@link
 952      * SecurityException} to be thrown.
 953      *
 954      * <p> If this thread is blocked in an invocation of the {@link
 955      * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
 956      * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
 957      * class, or of the {@link #join()}, {@link #join(long)}, {@link
 958      * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
 959      * methods of this class, then its interrupt status will be cleared and it
 960      * will receive an {@link InterruptedException}.
 961      *
 962      * <p> If this thread is blocked in an I/O operation upon an {@link
 963      * java.nio.channels.InterruptibleChannel InterruptibleChannel}
 964      * then the channel will be closed, the thread's interrupt
 965      * status will be set, and the thread will receive a {@link
 966      * java.nio.channels.ClosedByInterruptException}.
 967      *
 968      * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
 969      * then the thread's interrupt status will be set and it will return
 970      * immediately from the selection operation, possibly with a non-zero
 971      * value, just as if the selector's {@link
 972      * java.nio.channels.Selector#wakeup wakeup} method were invoked.
 973      *
 974      * <p> If none of the previous conditions hold then this thread's interrupt
 975      * status will be set. </p>
 976      *
 977      * <p> Interrupting a thread that is not alive need not have any effect.
 978      *
 979      * @throws  SecurityException
 980      *          if the current thread cannot modify this thread
 981      *
 982      * @revised 6.0
 983      * @spec JSR-51
 984      */
 985     public void interrupt() {
 986         if (this != Thread.currentThread()) {
 987             checkAccess();
 988 
 989             // thread may be blocked in an I/O operation
 990             synchronized (blockerLock) {
 991                 Interruptible b = blocker;
 992                 if (b != null) {
 993                     interrupt0();  // set interrupt status
 994                     b.interrupt(this);
 995                     return;
 996                 }
 997             }
 998         }
 999 
1000         // set interrupt status
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      * <p>A thread interruption ignored because a thread was not alive
1013      * at the time of the interrupt will be reflected by this method
1014      * returning false.
1015      *
1016      * @return  {@code true} if the current thread has been interrupted;
1017      *          {@code false} otherwise.
1018      * @see #isInterrupted()
1019      * @revised 6.0
1020      */
1021     public static boolean interrupted() {
1022         return currentThread().isInterrupted(true);
1023     }
1024 
1025     /**
1026      * Tests whether this thread has been interrupted.  The <i>interrupted
1027      * status</i> of the thread is unaffected by this method.
1028      *
1029      * <p>A thread interruption ignored because a thread was not alive
1030      * at the time of the interrupt will be reflected by this method
1031      * returning false.
1032      *
1033      * @return  {@code true} if this thread has been interrupted;
1034      *          {@code false} otherwise.
1035      * @see     #interrupted()
1036      * @revised 6.0
1037      */
1038     public boolean isInterrupted() {
1039         return isInterrupted(false);
1040     }
1041 
1042     /**
1043      * Tests if some Thread has been interrupted.  The interrupted state
1044      * is reset or not based on the value of ClearInterrupted that is
1045      * passed.
1046      */
1047     @HotSpotIntrinsicCandidate
1048     private native boolean isInterrupted(boolean ClearInterrupted);
1049 
1050     /**
1051      * Tests if this thread is alive. A thread is alive if it has
1052      * been started and has not yet died.
1053      *
1054      * @return  {@code true} if this thread is alive;
1055      *          {@code false} otherwise.
1056      */
1057     public final native boolean isAlive();
1058 
1059     /**
1060      * Suspends this thread.
1061      * <p>
1062      * First, the {@code checkAccess} method of this thread is called
1063      * with no arguments. This may result in throwing a
1064      * {@code SecurityException }(in the current thread).
1065      * <p>
1066      * If the thread is alive, it is suspended and makes no further
1067      * progress unless and until it is resumed.
1068      *
1069      * @throws     SecurityException  if the current thread cannot modify
1070      *             this thread.
1071      * @see #checkAccess
1072      * @deprecated   This method has been deprecated, as it is
1073      *   inherently deadlock-prone.  If the target thread holds a lock on the
1074      *   monitor protecting a critical system resource when it is suspended, no
1075      *   thread can access this resource until the target thread is resumed. If
1076      *   the thread that would resume the target thread attempts to lock this
1077      *   monitor prior to calling {@code resume}, deadlock results.  Such
1078      *   deadlocks typically manifest themselves as "frozen" processes.
1079      *   For more information, see
1080      *   <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
1081      *   are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1082      */
1083     @Deprecated(since="1.2")
1084     public final void suspend() {
1085         checkAccess();
1086         suspend0();
1087     }
1088 
1089     /**
1090      * Resumes a suspended thread.
1091      * <p>
1092      * First, the {@code checkAccess} method of this thread is called
1093      * with no arguments. This may result in throwing a
1094      * {@code SecurityException} (in the current thread).
1095      * <p>
1096      * If the thread is alive but suspended, it is resumed and is
1097      * permitted to make progress in its execution.
1098      *
1099      * @throws     SecurityException  if the current thread cannot modify this
1100      *             thread.
1101      * @see        #checkAccess
1102      * @see        #suspend()
1103      * @deprecated This method exists solely for use with {@link #suspend},
1104      *     which has been deprecated because it is deadlock-prone.
1105      *     For more information, see
1106      *     <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
1107      *     are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1108      */
1109     @Deprecated(since="1.2")
1110     public final void resume() {
1111         checkAccess();
1112         resume0();
1113     }
1114 
1115     /**
1116      * Changes the priority of this thread.
1117      * <p>
1118      * First the {@code checkAccess} method of this thread is called
1119      * with no arguments. This may result in throwing a {@code SecurityException}.
1120      * <p>
1121      * Otherwise, the priority of this thread is set to the smaller of
1122      * the specified {@code newPriority} and the maximum permitted
1123      * priority of the thread's thread group.
1124      *
1125      * @param newPriority priority to set this thread to
1126      * @throws     IllegalArgumentException  If the priority is not in the
1127      *               range {@code MIN_PRIORITY} to
1128      *               {@code MAX_PRIORITY}.
1129      * @throws     SecurityException  if the current thread cannot modify
1130      *               this thread.
1131      * @see        #getPriority
1132      * @see        #checkAccess()
1133      * @see        #getThreadGroup()
1134      * @see        #MAX_PRIORITY
1135      * @see        #MIN_PRIORITY
1136      * @see        ThreadGroup#getMaxPriority()
1137      */
1138     public final void setPriority(int newPriority) {
1139         ThreadGroup g;
1140         checkAccess();
1141         if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
1142             throw new IllegalArgumentException();
1143         }
1144         if((g = getThreadGroup()) != null) {
1145             if (newPriority > g.getMaxPriority()) {
1146                 newPriority = g.getMaxPriority();
1147             }
1148             setPriority0(priority = newPriority);
1149         }
1150     }
1151 
1152     /**
1153      * Returns this thread's priority.
1154      *
1155      * @return  this thread's priority.
1156      * @see     #setPriority
1157      */
1158     public final int getPriority() {
1159         return priority;
1160     }
1161 
1162     /**
1163      * Changes the name of this thread to be equal to the argument {@code name}.
1164      * <p>
1165      * First the {@code checkAccess} method of this thread is called
1166      * with no arguments. This may result in throwing a
1167      * {@code SecurityException}.
1168      *
1169      * @param      name   the new name for this thread.
1170      * @throws     SecurityException  if the current thread cannot modify this
1171      *             thread.
1172      * @see        #getName
1173      * @see        #checkAccess()
1174      */
1175     public final synchronized void setName(String name) {
1176         checkAccess();
1177         if (name == null) {
1178             throw new NullPointerException("name cannot be null");
1179         }
1180 
1181         this.name = name;
1182         if (threadStatus != 0) {
1183             setNativeName(name);
1184         }
1185     }
1186 
1187     /**
1188      * Returns this thread's name.
1189      *
1190      * @return  this thread's name.
1191      * @see     #setName(String)
1192      */
1193     public final String getName() {
1194         return name;
1195     }
1196 
1197     /**
1198      * Returns the thread group to which this thread belongs.
1199      * This method returns null if this thread has died
1200      * (been stopped).
1201      *
1202      * @return  this thread's thread group.
1203      */
1204     public final ThreadGroup getThreadGroup() {
1205         return group;
1206     }
1207 
1208     /**
1209      * Returns an estimate of the number of active threads in the current
1210      * thread's {@linkplain java.lang.ThreadGroup thread group} and its
1211      * subgroups. Recursively iterates over all subgroups in the current
1212      * thread's thread group.
1213      *
1214      * <p> The value returned is only an estimate because the number of
1215      * threads may change dynamically while this method traverses internal
1216      * data structures, and might be affected by the presence of certain
1217      * system threads. This method is intended primarily for debugging
1218      * and monitoring purposes.
1219      *
1220      * @return  an estimate of the number of active threads in the current
1221      *          thread's thread group and in any other thread group that
1222      *          has the current thread's thread group as an ancestor
1223      */
1224     public static int activeCount() {
1225         return currentThread().getThreadGroup().activeCount();
1226     }
1227 
1228     /**
1229      * Copies into the specified array every active thread in the current
1230      * thread's thread group and its subgroups. This method simply
1231      * invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])}
1232      * method of the current thread's thread group.
1233      *
1234      * <p> An application might use the {@linkplain #activeCount activeCount}
1235      * method to get an estimate of how big the array should be, however
1236      * <i>if the array is too short to hold all the threads, the extra threads
1237      * are silently ignored.</i>  If it is critical to obtain every active
1238      * thread in the current thread's thread group and its subgroups, the
1239      * invoker should verify that the returned int value is strictly less
1240      * than the length of {@code tarray}.
1241      *
1242      * <p> Due to the inherent race condition in this method, it is recommended
1243      * that the method only be used for debugging and monitoring purposes.
1244      *
1245      * @param  tarray
1246      *         an array into which to put the list of threads
1247      *
1248      * @return  the number of threads put into the array
1249      *
1250      * @throws  SecurityException
1251      *          if {@link java.lang.ThreadGroup#checkAccess} determines that
1252      *          the current thread cannot access its thread group
1253      */
1254     public static int enumerate(Thread tarray[]) {
1255         return currentThread().getThreadGroup().enumerate(tarray);
1256     }
1257 
1258     /**
1259      * Counts the number of stack frames in this thread. The thread must
1260      * be suspended.
1261      *
1262      * @return     the number of stack frames in this thread.
1263      * @throws     IllegalThreadStateException  if this thread is not
1264      *             suspended.
1265      * @deprecated The definition of this call depends on {@link #suspend},
1266      *             which is deprecated.  Further, the results of this call
1267      *             were never well-defined.
1268      *             This method is subject to removal in a future version of Java SE.
1269      * @see        StackWalker
1270      */
1271     @Deprecated(since="1.2", forRemoval=true)
1272     public native int countStackFrames();
1273 
1274     /**
1275      * Waits at most {@code millis} milliseconds for this thread to
1276      * die. A timeout of {@code 0} means to wait forever.
1277      *
1278      * <p> This implementation uses a loop of {@code this.wait} calls
1279      * conditioned on {@code this.isAlive}. As a thread terminates the
1280      * {@code this.notifyAll} method is invoked. It is recommended that
1281      * applications not use {@code wait}, {@code notify}, or
1282      * {@code notifyAll} on {@code Thread} instances.
1283      *
1284      * @param  millis
1285      *         the time to wait in milliseconds
1286      *
1287      * @throws  IllegalArgumentException
1288      *          if the value of {@code millis} is negative
1289      *
1290      * @throws  InterruptedException
1291      *          if any thread has interrupted the current thread. The
1292      *          <i>interrupted status</i> of the current thread is
1293      *          cleared when this exception is thrown.
1294      */
1295     public final synchronized void join(final long millis)
1296     throws InterruptedException {
1297         if (millis > 0) {
1298             if (isAlive()) {
1299                 final long startTime = System.nanoTime();
1300                 long delay = millis;
1301                 do {
1302                     wait(delay);
1303                 } while (isAlive() && (delay = millis -
1304                         TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)) > 0);
1305             }
1306         } else if (millis == 0) {
1307             while (isAlive()) {
1308                 wait(0);
1309             }
1310         } else {
1311             throw new IllegalArgumentException("timeout value is negative");
1312         }
1313     }
1314 
1315     /**
1316      * Waits at most {@code millis} milliseconds plus
1317      * {@code nanos} nanoseconds for this thread to die.
1318      * If both arguments are {@code 0}, it means to wait forever.
1319      *
1320      * <p> This implementation uses a loop of {@code this.wait} calls
1321      * conditioned on {@code this.isAlive}. As a thread terminates the
1322      * {@code this.notifyAll} method is invoked. It is recommended that
1323      * applications not use {@code wait}, {@code notify}, or
1324      * {@code notifyAll} on {@code Thread} instances.
1325      *
1326      * @param  millis
1327      *         the time to wait in milliseconds
1328      *
1329      * @param  nanos
1330      *         {@code 0-999999} additional nanoseconds to wait
1331      *
1332      * @throws  IllegalArgumentException
1333      *          if the value of {@code millis} is negative, or the value
1334      *          of {@code nanos} is not in the range {@code 0-999999}
1335      *
1336      * @throws  InterruptedException
1337      *          if any thread has interrupted the current thread. The
1338      *          <i>interrupted status</i> of the current thread is
1339      *          cleared when this exception is thrown.
1340      */
1341     public final synchronized void join(long millis, int nanos)
1342     throws InterruptedException {
1343 
1344         if (millis < 0) {
1345             throw new IllegalArgumentException("timeout value is negative");
1346         }
1347 
1348         if (nanos < 0 || nanos > 999999) {
1349             throw new IllegalArgumentException(
1350                                 "nanosecond timeout value out of range");
1351         }
1352 
1353         if (nanos > 0 && millis < Long.MAX_VALUE) {
1354             millis++;
1355         }
1356 
1357         join(millis);
1358     }
1359 
1360     /**
1361      * Waits for this thread to die.
1362      *
1363      * <p> An invocation of this method behaves in exactly the same
1364      * way as the invocation
1365      *
1366      * <blockquote>
1367      * {@linkplain #join(long) join}{@code (0)}
1368      * </blockquote>
1369      *
1370      * @throws  InterruptedException
1371      *          if any thread has interrupted the current thread. The
1372      *          <i>interrupted status</i> of the current thread is
1373      *          cleared when this exception is thrown.
1374      */
1375     public final void join() throws InterruptedException {
1376         join(0);
1377     }
1378 
1379     /**
1380      * Prints a stack trace of the current thread to the standard error stream.
1381      * This method is used only for debugging.
1382      */
1383     public static void dumpStack() {
1384         new Exception("Stack trace").printStackTrace();
1385     }
1386 
1387     /**
1388      * Marks this thread as either a {@linkplain #isDaemon daemon} thread
1389      * or a user thread. The Java Virtual Machine exits when the only
1390      * threads running are all daemon threads.
1391      *
1392      * <p> This method must be invoked before the thread is started.
1393      *
1394      * @param  on
1395      *         if {@code true}, marks this thread as a daemon thread
1396      *
1397      * @throws  IllegalThreadStateException
1398      *          if this thread is {@linkplain #isAlive alive}
1399      *
1400      * @throws  SecurityException
1401      *          if {@link #checkAccess} determines that the current
1402      *          thread cannot modify this thread
1403      */
1404     public final void setDaemon(boolean on) {
1405         checkAccess();
1406         if (isAlive()) {
1407             throw new IllegalThreadStateException();
1408         }
1409         daemon = on;
1410     }
1411 
1412     /**
1413      * Tests if this thread is a daemon thread.
1414      *
1415      * @return  {@code true} if this thread is a daemon thread;
1416      *          {@code false} otherwise.
1417      * @see     #setDaemon(boolean)
1418      */
1419     public final boolean isDaemon() {
1420         return daemon;
1421     }
1422 
1423     /**
1424      * Determines if the currently running thread has permission to
1425      * modify this thread.
1426      * <p>
1427      * If there is a security manager, its {@code checkAccess} method
1428      * is called with this thread as its argument. This may result in
1429      * throwing a {@code SecurityException}.
1430      *
1431      * @throws  SecurityException  if the current thread is not allowed to
1432      *          access this thread.
1433      * @see        SecurityManager#checkAccess(Thread)
1434      */
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                 Object referent = get();
2055                 return (referent != null) &&
2056                        (referent == ((WeakClassKey) obj).get());
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 native void setNativeName(String name);
2089 }