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