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