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