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