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