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