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