1 /*
   2  * Copyright (c) 1994, 2018, 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.misc.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      *
1319      * <p> This implementation uses a loop of {@code this.wait} calls
1320      * conditioned on {@code this.isAlive}. As a thread terminates the
1321      * {@code this.notifyAll} method is invoked. It is recommended that
1322      * applications not use {@code wait}, {@code notify}, or
1323      * {@code notifyAll} on {@code Thread} instances.
1324      *
1325      * @param  millis
1326      *         the time to wait in milliseconds
1327      *
1328      * @param  nanos
1329      *         {@code 0-999999} additional nanoseconds to wait
1330      *
1331      * @throws  IllegalArgumentException
1332      *          if the value of {@code millis} is negative, or the value
1333      *          of {@code nanos} is not in the range {@code 0-999999}
1334      *
1335      * @throws  InterruptedException
1336      *          if any thread has interrupted the current thread. The
1337      *          <i>interrupted status</i> of the current thread is
1338      *          cleared when this exception is thrown.
1339      */
1340     public final synchronized void join(long millis, int nanos)
1341     throws InterruptedException {
1342 
1343         if (millis < 0) {
1344             throw new IllegalArgumentException("timeout value is negative");
1345         }
1346 
1347         if (nanos < 0 || nanos > 999999) {
1348             throw new IllegalArgumentException(
1349                                 "nanosecond timeout value out of range");
1350         }
1351 
1352         if (nanos > 0 && millis < Long.MAX_VALUE) {
1353             millis++;
1354         }
1355 
1356         join(millis);
1357     }
1358 
1359     /**
1360      * Waits for this thread to die.
1361      *
1362      * <p> An invocation of this method behaves in exactly the same
1363      * way as the invocation
1364      *
1365      * <blockquote>
1366      * {@linkplain #join(long) join}{@code (0)}
1367      * </blockquote>
1368      *
1369      * @throws  InterruptedException
1370      *          if any thread has interrupted the current thread. The
1371      *          <i>interrupted status</i> of the current thread is
1372      *          cleared when this exception is thrown.
1373      */
1374     public final void join() throws InterruptedException {
1375         join(0);
1376     }
1377 
1378     /**
1379      * Prints a stack trace of the current thread to the standard error stream.
1380      * This method is used only for debugging.
1381      */
1382     public static void dumpStack() {
1383         new Exception("Stack trace").printStackTrace();
1384     }
1385 
1386     /**
1387      * Marks this thread as either a {@linkplain #isDaemon daemon} thread
1388      * or a user thread. The Java Virtual Machine exits when the only
1389      * threads running are all daemon threads.
1390      *
1391      * <p> This method must be invoked before the thread is started.
1392      *
1393      * @param  on
1394      *         if {@code true}, marks this thread as a daemon thread
1395      *
1396      * @throws  IllegalThreadStateException
1397      *          if this thread is {@linkplain #isAlive alive}
1398      *
1399      * @throws  SecurityException
1400      *          if {@link #checkAccess} determines that the current
1401      *          thread cannot modify this thread
1402      */
1403     public final void setDaemon(boolean on) {
1404         checkAccess();
1405         if (isAlive()) {
1406             throw new IllegalThreadStateException();
1407         }
1408         daemon = on;
1409     }
1410 
1411     /**
1412      * Tests if this thread is a daemon thread.
1413      *
1414      * @return  {@code true} if this thread is a daemon thread;
1415      *          {@code false} otherwise.
1416      * @see     #setDaemon(boolean)
1417      */
1418     public final boolean isDaemon() {
1419         return daemon;
1420     }
1421 
1422     /**
1423      * Determines if the currently running thread has permission to
1424      * modify this thread.
1425      * <p>
1426      * If there is a security manager, its {@code checkAccess} method
1427      * is called with this thread as its argument. This may result in
1428      * throwing a {@code SecurityException}.
1429      *
1430      * @throws  SecurityException  if the current thread is not allowed to
1431      *          access this thread.
1432      * @see        SecurityManager#checkAccess(Thread)
1433      */
1434     public final void checkAccess() {
1435         SecurityManager security = System.getSecurityManager();
1436         if (security != null) {
1437             security.checkAccess(this);
1438         }
1439     }
1440 
1441     /**
1442      * Returns a string representation of this thread, including the
1443      * thread's name, priority, and thread group.
1444      *
1445      * @return  a string representation of this thread.
1446      */
1447     public String toString() {
1448         ThreadGroup group = getThreadGroup();
1449         if (group != null) {
1450             return "Thread[" + getName() + "," + getPriority() + "," +
1451                            group.getName() + "]";
1452         } else {
1453             return "Thread[" + getName() + "," + getPriority() + "," +
1454                             "" + "]";
1455         }
1456     }
1457 
1458     /**
1459      * Returns the context {@code ClassLoader} for this thread. The context
1460      * {@code ClassLoader} is provided by the creator of the thread for use
1461      * by code running in this thread when loading classes and resources.
1462      * If not {@linkplain #setContextClassLoader set}, the default is the
1463      * {@code ClassLoader} context of the parent thread. The context
1464      * {@code ClassLoader} of the
1465      * primordial thread is typically set to the class loader used to load the
1466      * application.
1467      *
1468      *
1469      * @return  the context {@code ClassLoader} for this thread, or {@code null}
1470      *          indicating the system class loader (or, failing that, the
1471      *          bootstrap class loader)
1472      *
1473      * @throws  SecurityException
1474      *          if a security manager is present, and the caller's class loader
1475      *          is not {@code null} and is not the same as or an ancestor of the
1476      *          context class loader, and the caller does not have the
1477      *          {@link RuntimePermission}{@code ("getClassLoader")}
1478      *
1479      * @since 1.2
1480      */
1481     @CallerSensitive
1482     public ClassLoader getContextClassLoader() {
1483         if (contextClassLoader == null)
1484             return null;
1485         SecurityManager sm = System.getSecurityManager();
1486         if (sm != null) {
1487             ClassLoader.checkClassLoaderPermission(contextClassLoader,
1488                                                    Reflection.getCallerClass());
1489         }
1490         return contextClassLoader;
1491     }
1492 
1493     /**
1494      * Sets the context ClassLoader for this Thread. The context
1495      * ClassLoader can be set when a thread is created, and allows
1496      * the creator of the thread to provide the appropriate class loader,
1497      * through {@code getContextClassLoader}, to code running in the thread
1498      * when loading classes and resources.
1499      *
1500      * <p>If a security manager is present, its {@link
1501      * SecurityManager#checkPermission(java.security.Permission) checkPermission}
1502      * method is invoked with a {@link RuntimePermission RuntimePermission}{@code
1503      * ("setContextClassLoader")} permission to see if setting the context
1504      * ClassLoader is permitted.
1505      *
1506      * @param  cl
1507      *         the context ClassLoader for this Thread, or null  indicating the
1508      *         system class loader (or, failing that, the bootstrap class loader)
1509      *
1510      * @throws  SecurityException
1511      *          if the current thread cannot set the context ClassLoader
1512      *
1513      * @since 1.2
1514      */
1515     public void setContextClassLoader(ClassLoader cl) {
1516         SecurityManager sm = System.getSecurityManager();
1517         if (sm != null) {
1518             sm.checkPermission(new RuntimePermission("setContextClassLoader"));
1519         }
1520         contextClassLoader = cl;
1521     }
1522 
1523     /**
1524      * Returns {@code true} if and only if the current thread holds the
1525      * monitor lock on the specified object.
1526      *
1527      * <p>This method is designed to allow a program to assert that
1528      * the current thread already holds a specified lock:
1529      * <pre>
1530      *     assert Thread.holdsLock(obj);
1531      * </pre>
1532      *
1533      * @param  obj the object on which to test lock ownership
1534      * @throws NullPointerException if obj is {@code null}
1535      * @return {@code true} if the current thread holds the monitor lock on
1536      *         the specified object.
1537      * @since 1.4
1538      */
1539     public static native boolean holdsLock(Object obj);
1540 
1541     private static final StackTraceElement[] EMPTY_STACK_TRACE
1542         = new StackTraceElement[0];
1543 
1544     /**
1545      * Returns an array of stack trace elements representing the stack dump
1546      * of this thread.  This method will return a zero-length array if
1547      * this thread has not started, has started but has not yet been
1548      * scheduled to run by the system, or has terminated.
1549      * If the returned array is of non-zero length then the first element of
1550      * the array represents the top of the stack, which is the most recent
1551      * method invocation in the sequence.  The last element of the array
1552      * represents the bottom of the stack, which is the least recent method
1553      * invocation in the sequence.
1554      *
1555      * <p>If there is a security manager, and this thread is not
1556      * the current thread, then the security manager's
1557      * {@code checkPermission} method is called with a
1558      * {@code RuntimePermission("getStackTrace")} permission
1559      * to see if it's ok to get the stack trace.
1560      *
1561      * <p>Some virtual machines may, under some circumstances, omit one
1562      * or more stack frames from the stack trace.  In the extreme case,
1563      * a virtual machine that has no stack trace information concerning
1564      * this thread is permitted to return a zero-length array from this
1565      * method.
1566      *
1567      * @return an array of {@code StackTraceElement},
1568      * each represents one stack frame.
1569      *
1570      * @throws SecurityException
1571      *        if a security manager exists and its
1572      *        {@code checkPermission} method doesn't allow
1573      *        getting the stack trace of thread.
1574      * @see SecurityManager#checkPermission
1575      * @see RuntimePermission
1576      * @see Throwable#getStackTrace
1577      *
1578      * @since 1.5
1579      */
1580     public StackTraceElement[] getStackTrace() {
1581         if (this != Thread.currentThread()) {
1582             // check for getStackTrace permission
1583             SecurityManager security = System.getSecurityManager();
1584             if (security != null) {
1585                 security.checkPermission(
1586                     SecurityConstants.GET_STACK_TRACE_PERMISSION);
1587             }
1588             // optimization so we do not call into the vm for threads that
1589             // have not yet started or have terminated
1590             if (!isAlive()) {
1591                 return EMPTY_STACK_TRACE;
1592             }
1593             StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
1594             StackTraceElement[] stackTrace = stackTraceArray[0];
1595             // a thread that was alive during the previous isAlive call may have
1596             // since terminated, therefore not having a stacktrace.
1597             if (stackTrace == null) {
1598                 stackTrace = EMPTY_STACK_TRACE;
1599             }
1600             return stackTrace;
1601         } else {
1602             return (new Exception()).getStackTrace();
1603         }
1604     }
1605 
1606     /**
1607      * Returns a map of stack traces for all live threads.
1608      * The map keys are threads and each map value is an array of
1609      * {@code StackTraceElement} that represents the stack dump
1610      * of the corresponding {@code Thread}.
1611      * The returned stack traces are in the format specified for
1612      * the {@link #getStackTrace getStackTrace} method.
1613      *
1614      * <p>The threads may be executing while this method is called.
1615      * The stack trace of each thread only represents a snapshot and
1616      * each stack trace may be obtained at different time.  A zero-length
1617      * array will be returned in the map value if the virtual machine has
1618      * no stack trace information about a thread.
1619      *
1620      * <p>If there is a security manager, then the security manager's
1621      * {@code checkPermission} method is called with a
1622      * {@code RuntimePermission("getStackTrace")} permission as well as
1623      * {@code RuntimePermission("modifyThreadGroup")} permission
1624      * to see if it is ok to get the stack trace of all threads.
1625      *
1626      * @return a {@code Map} from {@code Thread} to an array of
1627      * {@code StackTraceElement} that represents the stack trace of
1628      * the corresponding thread.
1629      *
1630      * @throws SecurityException
1631      *        if a security manager exists and its
1632      *        {@code checkPermission} method doesn't allow
1633      *        getting the stack trace of thread.
1634      * @see #getStackTrace
1635      * @see SecurityManager#checkPermission
1636      * @see RuntimePermission
1637      * @see Throwable#getStackTrace
1638      *
1639      * @since 1.5
1640      */
1641     public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
1642         // check for getStackTrace permission
1643         SecurityManager security = System.getSecurityManager();
1644         if (security != null) {
1645             security.checkPermission(
1646                 SecurityConstants.GET_STACK_TRACE_PERMISSION);
1647             security.checkPermission(
1648                 SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
1649         }
1650 
1651         // Get a snapshot of the list of all threads
1652         Thread[] threads = getThreads();
1653         StackTraceElement[][] traces = dumpThreads(threads);
1654         Map<Thread, StackTraceElement[]> m = new HashMap<>(threads.length);
1655         for (int i = 0; i < threads.length; i++) {
1656             StackTraceElement[] stackTrace = traces[i];
1657             if (stackTrace != null) {
1658                 m.put(threads[i], stackTrace);
1659             }
1660             // else terminated so we don't put it in the map
1661         }
1662         return m;
1663     }
1664 
1665     /** cache of subclass security audit results */
1666     /* Replace with ConcurrentReferenceHashMap when/if it appears in a future
1667      * release */
1668     private static class Caches {
1669         /** cache of subclass security audit results */
1670         static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
1671             new ConcurrentHashMap<>();
1672 
1673         /** queue for WeakReferences to audited subclasses */
1674         static final ReferenceQueue<Class<?>> subclassAuditsQueue =
1675             new ReferenceQueue<>();
1676     }
1677 
1678     /**
1679      * Verifies that this (possibly subclass) instance can be constructed
1680      * without violating security constraints: the subclass must not override
1681      * security-sensitive non-final methods, or else the
1682      * "enableContextClassLoaderOverride" RuntimePermission is checked.
1683      */
1684     private static boolean isCCLOverridden(Class<?> cl) {
1685         if (cl == Thread.class)
1686             return false;
1687 
1688         processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
1689         WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
1690         Boolean result = Caches.subclassAudits.get(key);
1691         if (result == null) {
1692             result = Boolean.valueOf(auditSubclass(cl));
1693             Caches.subclassAudits.putIfAbsent(key, result);
1694         }
1695 
1696         return result.booleanValue();
1697     }
1698 
1699     /**
1700      * Performs reflective checks on given subclass to verify that it doesn't
1701      * override security-sensitive non-final methods.  Returns true if the
1702      * subclass overrides any of the methods, false otherwise.
1703      */
1704     private static boolean auditSubclass(final Class<?> subcl) {
1705         Boolean result = AccessController.doPrivileged(
1706             new PrivilegedAction<>() {
1707                 public Boolean run() {
1708                     for (Class<?> cl = subcl;
1709                          cl != Thread.class;
1710                          cl = cl.getSuperclass())
1711                     {
1712                         try {
1713                             cl.getDeclaredMethod("getContextClassLoader", new Class<?>[0]);
1714                             return Boolean.TRUE;
1715                         } catch (NoSuchMethodException ex) {
1716                         }
1717                         try {
1718                             Class<?>[] params = {ClassLoader.class};
1719                             cl.getDeclaredMethod("setContextClassLoader", params);
1720                             return Boolean.TRUE;
1721                         } catch (NoSuchMethodException ex) {
1722                         }
1723                     }
1724                     return Boolean.FALSE;
1725                 }
1726             }
1727         );
1728         return result.booleanValue();
1729     }
1730 
1731     private static native StackTraceElement[][] dumpThreads(Thread[] threads);
1732     private static native Thread[] getThreads();
1733 
1734     /**
1735      * Returns the identifier of this Thread.  The thread ID is a positive
1736      * {@code long} number generated when this thread was created.
1737      * The thread ID is unique and remains unchanged during its lifetime.
1738      * When a thread is terminated, this thread ID may be reused.
1739      *
1740      * @return this thread's ID.
1741      * @since 1.5
1742      */
1743     public long getId() {
1744         return tid;
1745     }
1746 
1747     /**
1748      * A thread state.  A thread can be in one of the following states:
1749      * <ul>
1750      * <li>{@link #NEW}<br>
1751      *     A thread that has not yet started is in this state.
1752      *     </li>
1753      * <li>{@link #RUNNABLE}<br>
1754      *     A thread executing in the Java virtual machine is in this state.
1755      *     </li>
1756      * <li>{@link #BLOCKED}<br>
1757      *     A thread that is blocked waiting for a monitor lock
1758      *     is in this state.
1759      *     </li>
1760      * <li>{@link #WAITING}<br>
1761      *     A thread that is waiting indefinitely for another thread to
1762      *     perform a particular action is in this state.
1763      *     </li>
1764      * <li>{@link #TIMED_WAITING}<br>
1765      *     A thread that is waiting for another thread to perform an action
1766      *     for up to a specified waiting time is in this state.
1767      *     </li>
1768      * <li>{@link #TERMINATED}<br>
1769      *     A thread that has exited is in this state.
1770      *     </li>
1771      * </ul>
1772      *
1773      * <p>
1774      * A thread can be in only one state at a given point in time.
1775      * These states are virtual machine states which do not reflect
1776      * any operating system thread states.
1777      *
1778      * @since   1.5
1779      * @see #getState
1780      */
1781     public enum State {
1782         /**
1783          * Thread state for a thread which has not yet started.
1784          */
1785         NEW,
1786 
1787         /**
1788          * Thread state for a runnable thread.  A thread in the runnable
1789          * state is executing in the Java virtual machine but it may
1790          * be waiting for other resources from the operating system
1791          * such as processor.
1792          */
1793         RUNNABLE,
1794 
1795         /**
1796          * Thread state for a thread blocked waiting for a monitor lock.
1797          * A thread in the blocked state is waiting for a monitor lock
1798          * to enter a synchronized block/method or
1799          * reenter a synchronized block/method after calling
1800          * {@link Object#wait() Object.wait}.
1801          */
1802         BLOCKED,
1803 
1804         /**
1805          * Thread state for a waiting thread.
1806          * A thread is in the waiting state due to calling one of the
1807          * following methods:
1808          * <ul>
1809          *   <li>{@link Object#wait() Object.wait} with no timeout</li>
1810          *   <li>{@link #join() Thread.join} with no timeout</li>
1811          *   <li>{@link LockSupport#park() LockSupport.park}</li>
1812          * </ul>
1813          *
1814          * <p>A thread in the waiting state is waiting for another thread to
1815          * perform a particular action.
1816          *
1817          * For example, a thread that has called {@code Object.wait()}
1818          * on an object is waiting for another thread to call
1819          * {@code Object.notify()} or {@code Object.notifyAll()} on
1820          * that object. A thread that has called {@code Thread.join()}
1821          * is waiting for a specified thread to terminate.
1822          */
1823         WAITING,
1824 
1825         /**
1826          * Thread state for a waiting thread with a specified waiting time.
1827          * A thread is in the timed waiting state due to calling one of
1828          * the following methods with a specified positive waiting time:
1829          * <ul>
1830          *   <li>{@link #sleep Thread.sleep}</li>
1831          *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
1832          *   <li>{@link #join(long) Thread.join} with timeout</li>
1833          *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
1834          *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
1835          * </ul>
1836          */
1837         TIMED_WAITING,
1838 
1839         /**
1840          * Thread state for a terminated thread.
1841          * The thread has completed execution.
1842          */
1843         TERMINATED;
1844     }
1845 
1846     /**
1847      * Returns the state of this thread.
1848      * This method is designed for use in monitoring of the system state,
1849      * not for synchronization control.
1850      *
1851      * @return this thread's state.
1852      * @since 1.5
1853      */
1854     public State getState() {
1855         // get current thread state
1856         return jdk.internal.misc.VM.toThreadState(threadStatus);
1857     }
1858 
1859     // Added in JSR-166
1860 
1861     /**
1862      * Interface for handlers invoked when a {@code Thread} abruptly
1863      * terminates due to an uncaught exception.
1864      * <p>When a thread is about to terminate due to an uncaught exception
1865      * the Java Virtual Machine will query the thread for its
1866      * {@code UncaughtExceptionHandler} using
1867      * {@link #getUncaughtExceptionHandler} and will invoke the handler's
1868      * {@code uncaughtException} method, passing the thread and the
1869      * exception as arguments.
1870      * If a thread has not had its {@code UncaughtExceptionHandler}
1871      * explicitly set, then its {@code ThreadGroup} object acts as its
1872      * {@code UncaughtExceptionHandler}. If the {@code ThreadGroup} object
1873      * has no
1874      * special requirements for dealing with the exception, it can forward
1875      * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
1876      * default uncaught exception handler}.
1877      *
1878      * @see #setDefaultUncaughtExceptionHandler
1879      * @see #setUncaughtExceptionHandler
1880      * @see ThreadGroup#uncaughtException
1881      * @since 1.5
1882      */
1883     @FunctionalInterface
1884     public interface UncaughtExceptionHandler {
1885         /**
1886          * Method invoked when the given thread terminates due to the
1887          * given uncaught exception.
1888          * <p>Any exception thrown by this method will be ignored by the
1889          * Java Virtual Machine.
1890          * @param t the thread
1891          * @param e the exception
1892          */
1893         void uncaughtException(Thread t, Throwable e);
1894     }
1895 
1896     // null unless explicitly set
1897     private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
1898 
1899     // null unless explicitly set
1900     private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
1901 
1902     /**
1903      * Set the default handler invoked when a thread abruptly terminates
1904      * due to an uncaught exception, and no other handler has been defined
1905      * for that thread.
1906      *
1907      * <p>Uncaught exception handling is controlled first by the thread, then
1908      * by the thread's {@link ThreadGroup} object and finally by the default
1909      * uncaught exception handler. If the thread does not have an explicit
1910      * uncaught exception handler set, and the thread's thread group
1911      * (including parent thread groups)  does not specialize its
1912      * {@code uncaughtException} method, then the default handler's
1913      * {@code uncaughtException} method will be invoked.
1914      * <p>By setting the default uncaught exception handler, an application
1915      * can change the way in which uncaught exceptions are handled (such as
1916      * logging to a specific device, or file) for those threads that would
1917      * already accept whatever &quot;default&quot; behavior the system
1918      * provided.
1919      *
1920      * <p>Note that the default uncaught exception handler should not usually
1921      * defer to the thread's {@code ThreadGroup} object, as that could cause
1922      * infinite recursion.
1923      *
1924      * @param eh the object to use as the default uncaught exception handler.
1925      * If {@code null} then there is no default handler.
1926      *
1927      * @throws SecurityException if a security manager is present and it denies
1928      *         {@link RuntimePermission}{@code ("setDefaultUncaughtExceptionHandler")}
1929      *
1930      * @see #setUncaughtExceptionHandler
1931      * @see #getUncaughtExceptionHandler
1932      * @see ThreadGroup#uncaughtException
1933      * @since 1.5
1934      */
1935     public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
1936         SecurityManager sm = System.getSecurityManager();
1937         if (sm != null) {
1938             sm.checkPermission(
1939                 new RuntimePermission("setDefaultUncaughtExceptionHandler")
1940                     );
1941         }
1942 
1943          defaultUncaughtExceptionHandler = eh;
1944      }
1945 
1946     /**
1947      * Returns the default handler invoked when a thread abruptly terminates
1948      * due to an uncaught exception. If the returned value is {@code null},
1949      * there is no default.
1950      * @since 1.5
1951      * @see #setDefaultUncaughtExceptionHandler
1952      * @return the default uncaught exception handler for all threads
1953      */
1954     public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
1955         return defaultUncaughtExceptionHandler;
1956     }
1957 
1958     /**
1959      * Returns the handler invoked when this thread abruptly terminates
1960      * due to an uncaught exception. If this thread has not had an
1961      * uncaught exception handler explicitly set then this thread's
1962      * {@code ThreadGroup} object is returned, unless this thread
1963      * has terminated, in which case {@code null} is returned.
1964      * @since 1.5
1965      * @return the uncaught exception handler for this thread
1966      */
1967     public UncaughtExceptionHandler getUncaughtExceptionHandler() {
1968         return uncaughtExceptionHandler != null ?
1969             uncaughtExceptionHandler : group;
1970     }
1971 
1972     /**
1973      * Set the handler invoked when this thread abruptly terminates
1974      * due to an uncaught exception.
1975      * <p>A thread can take full control of how it responds to uncaught
1976      * exceptions by having its uncaught exception handler explicitly set.
1977      * If no such handler is set then the thread's {@code ThreadGroup}
1978      * object acts as its handler.
1979      * @param eh the object to use as this thread's uncaught exception
1980      * handler. If {@code null} then this thread has no explicit handler.
1981      * @throws  SecurityException  if the current thread is not allowed to
1982      *          modify this thread.
1983      * @see #setDefaultUncaughtExceptionHandler
1984      * @see ThreadGroup#uncaughtException
1985      * @since 1.5
1986      */
1987     public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
1988         checkAccess();
1989         uncaughtExceptionHandler = eh;
1990     }
1991 
1992     /**
1993      * Dispatch an uncaught exception to the handler. This method is
1994      * intended to be called only by the JVM.
1995      */
1996     private void dispatchUncaughtException(Throwable e) {
1997         getUncaughtExceptionHandler().uncaughtException(this, e);
1998     }
1999 
2000     /**
2001      * Removes from the specified map any keys that have been enqueued
2002      * on the specified reference queue.
2003      */
2004     static void processQueue(ReferenceQueue<Class<?>> queue,
2005                              ConcurrentMap<? extends
2006                              WeakReference<Class<?>>, ?> map)
2007     {
2008         Reference<? extends Class<?>> ref;
2009         while((ref = queue.poll()) != null) {
2010             map.remove(ref);
2011         }
2012     }
2013 
2014     /**
2015      *  Weak key for Class objects.
2016      **/
2017     static class WeakClassKey extends WeakReference<Class<?>> {
2018         /**
2019          * saved value of the referent's identity hash code, to maintain
2020          * a consistent hash code after the referent has been cleared
2021          */
2022         private final int hash;
2023 
2024         /**
2025          * Create a new WeakClassKey to the given object, registered
2026          * with a queue.
2027          */
2028         WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) {
2029             super(cl, refQueue);
2030             hash = System.identityHashCode(cl);
2031         }
2032 
2033         /**
2034          * Returns the identity hash code of the original referent.
2035          */
2036         @Override
2037         public int hashCode() {
2038             return hash;
2039         }
2040 
2041         /**
2042          * Returns true if the given object is this identical
2043          * WeakClassKey instance, or, if this object's referent has not
2044          * been cleared, if the given object is another WeakClassKey
2045          * instance with the identical non-null referent as this one.
2046          */
2047         @Override
2048         public boolean equals(Object obj) {
2049             if (obj == this)
2050                 return true;
2051 
2052             if (obj instanceof WeakClassKey) {
2053                 Object referent = get();
2054                 return (referent != null) &&
2055                        (referent == ((WeakClassKey) obj).get());
2056             } else {
2057                 return false;
2058             }
2059         }
2060     }
2061 
2062 
2063     // The following three initially uninitialized fields are exclusively
2064     // managed by class java.util.concurrent.ThreadLocalRandom. These
2065     // fields are used to build the high-performance PRNGs in the
2066     // concurrent code, and we can not risk accidental false sharing.
2067     // Hence, the fields are isolated with @Contended.
2068 
2069     /** The current seed for a ThreadLocalRandom */
2070     @jdk.internal.vm.annotation.Contended("tlr")
2071     long threadLocalRandomSeed;
2072 
2073     /** Probe hash value; nonzero if threadLocalRandomSeed initialized */
2074     @jdk.internal.vm.annotation.Contended("tlr")
2075     int threadLocalRandomProbe;
2076 
2077     /** Secondary seed isolated from public ThreadLocalRandom sequence */
2078     @jdk.internal.vm.annotation.Contended("tlr")
2079     int threadLocalRandomSecondarySeed;
2080 
2081     /* Some private helper methods */
2082     private native void setPriority0(int newPriority);
2083     private native void stop0(Object o);
2084     private native void suspend0();
2085     private native void resume0();
2086     private native void interrupt0();
2087     private native void setNativeName(String name);
2088 }