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