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