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