2 * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
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.
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).
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.
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
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;
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.security.util.SecurityConstants;
44 * A <i>thread</i> is a thread of execution in a program. The Java
45 * Virtual Machine allows an application to have multiple threads of
46 * execution running concurrently.
48 * Every thread has a priority. Threads with higher priority are
49 * executed in preference to threads with lower priority. Each thread
50 * may or may not also be marked as a daemon. When code running in
51 * some thread creates a new <code>Thread</code> object, the new
52 * thread has its priority initially set equal to the priority of the
53 * creating thread, and is a daemon thread if and only if the
54 * creating thread is a daemon.
56 * When a Java Virtual Machine starts up, there is usually a single
57 * non-daemon thread (which typically calls the method named
58 * <code>main</code> of some designated class). The Java Virtual
59 * Machine continues to execute threads until either of the following
62 * <li>The <code>exit</code> method of class <code>Runtime</code> has been
63 * called and the security manager has permitted the exit operation
65 * <li>All threads that are not daemon threads have died, either by
66 * returning from the call to the <code>run</code> method or by
67 * throwing an exception that propagates beyond the <code>run</code>
71 * There are two ways to create a new thread of execution. One is to
72 * declare a class to be a subclass of <code>Thread</code>. This
73 * subclass should override the <code>run</code> method of class
74 * <code>Thread</code>. An instance of the subclass can then be
75 * allocated and started. For example, a thread that computes primes
76 * larger than a stated value could be written as follows:
77 * <p><hr><blockquote><pre>
78 * class PrimeThread extends Thread {
80 * PrimeThread(long minPrime) {
81 * this.minPrime = minPrime;
85 * // compute primes larger than minPrime
86 * . . .
89 * </pre></blockquote><hr>
91 * The following code would then create a thread and start it running:
92 * <p><blockquote><pre>
93 * PrimeThread p = new PrimeThread(143);
97 * The other way to create a thread is to declare a class that
98 * implements the <code>Runnable</code> interface. That class then
99 * implements the <code>run</code> method. An instance of the class can
100 * then be allocated, passed as an argument when creating
101 * <code>Thread</code>, and started. The same example in this other
102 * style looks like the following:
103 * <p><hr><blockquote><pre>
104 * class PrimeRun implements Runnable {
106 * PrimeRun(long minPrime) {
107 * this.minPrime = minPrime;
110 * public void run() {
111 * // compute primes larger than minPrime
112 * . . .
115 * </pre></blockquote><hr>
117 * The following code would then create a thread and start it running:
118 * <p><blockquote><pre>
119 * PrimeRun p = new PrimeRun(143);
120 * new Thread(p).start();
121 * </pre></blockquote>
123 * Every thread has a name for identification purposes. More than
124 * one thread may have the same name. If a name is not specified when
125 * a thread is created, a new name is generated for it.
127 * Unless otherwise noted, passing a {@code null} argument to a constructor
128 * or method in this class will cause a {@link NullPointerException} to be
133 * @see Runtime#exit(int)
139 class Thread implements Runnable {
140 /* Make sure registerNatives is the first thing <clinit> does. */
141 private static native void registerNatives();
147 private int priority;
148 private Thread threadQ;
151 /* Whether or not to single_step this thread. */
152 private boolean single_step;
154 /* Whether or not the thread is a daemon thread. */
155 private boolean daemon = false;
158 private boolean stillborn = false;
160 /* What will be run. */
161 private Runnable target;
163 /* The group of this thread */
164 private ThreadGroup group;
166 /* The context ClassLoader for this thread */
167 private ClassLoader contextClassLoader;
169 /* The inherited AccessControlContext of this thread */
170 private AccessControlContext inheritedAccessControlContext;
172 /* For autonumbering anonymous threads. */
173 private static int threadInitNumber;
174 private static synchronized int nextThreadNum() {
175 return threadInitNumber++;
178 /* ThreadLocal values pertaining to this thread. This map is maintained
179 * by the ThreadLocal class. */
180 ThreadLocal.ThreadLocalMap threadLocals = null;
183 * InheritableThreadLocal values pertaining to this thread. This map is
184 * maintained by the InheritableThreadLocal class.
186 ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
189 * The requested stack size for this thread, or 0 if the creator did
190 * not specify a stack size. It is up to the VM to do whatever it
191 * likes with this number; some VMs will ignore it.
193 private long stackSize;
196 * JVM-private state that persists after native thread termination.
198 private long nativeParkEventPointer;
205 /* For generating thread ID */
206 private static long threadSeqNumber;
208 /* Java thread status for tools,
209 * initialized to indicate thread 'not yet started'
212 private volatile int threadStatus = 0;
215 private static synchronized long nextThreadID() {
216 return ++threadSeqNumber;
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
225 volatile Object parkBlocker;
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.
231 private volatile Interruptible blocker;
232 private final Object blockerLock = new Object();
234 /* Set the blocker field; invoked via sun.misc.SharedSecrets from java.nio code
236 void blockedOn(Interruptible b) {
237 synchronized (blockerLock) {
243 * The minimum priority that a thread can have.
245 public final static int MIN_PRIORITY = 1;
248 * The default priority that is assigned to a thread.
250 public final static int NORM_PRIORITY = 5;
253 * The maximum priority that a thread can have.
255 public final static int MAX_PRIORITY = 10;
258 * Returns a reference to the currently executing thread object.
260 * @return the currently executing thread.
262 public static native Thread currentThread();
265 * A hint to the scheduler that the current thread is willing to yield
266 * its current use of a processor. The scheduler is free to ignore this
269 * <p> Yield is a heuristic attempt to improve relative progression
270 * between threads that would otherwise over-utilise a CPU. Its use
271 * should be combined with detailed profiling and benchmarking to
272 * ensure that it actually has the desired effect.
274 * <p> It is rarely appropriate to use this method. It may be useful
275 * for debugging or testing purposes, where it may help to reproduce
276 * bugs due to race conditions. It may also be useful when designing
277 * concurrency control constructs such as the ones in the
278 * {@link java.util.concurrent.locks} package.
280 public static native void yield();
283 * Causes the currently executing thread to sleep (temporarily cease
284 * execution) for the specified number of milliseconds, subject to
285 * the precision and accuracy of system timers and schedulers. The thread
286 * does not lose ownership of any monitors.
289 * the length of time to sleep in milliseconds
291 * @throws IllegalArgumentException
292 * if the value of {@code millis} is negative
294 * @throws InterruptedException
295 * if any thread has interrupted the current thread. The
296 * <i>interrupted status</i> of the current thread is
297 * cleared when this exception is thrown.
299 public static native void sleep(long millis) throws InterruptedException;
302 * Causes the currently executing thread to sleep (temporarily cease
303 * execution) for the specified number of milliseconds plus the specified
304 * number of nanoseconds, subject to the precision and accuracy of system
305 * timers and schedulers. The thread does not lose ownership of any
309 * the length of time to sleep in milliseconds
312 * {@code 0-999999} additional nanoseconds to sleep
314 * @throws IllegalArgumentException
315 * if the value of {@code millis} is negative, or the value of
316 * {@code nanos} is not in the range {@code 0-999999}
318 * @throws InterruptedException
319 * if any thread has interrupted the current thread. The
320 * <i>interrupted status</i> of the current thread is
321 * cleared when this exception is thrown.
323 public static void sleep(long millis, int nanos)
324 throws InterruptedException {
326 throw new IllegalArgumentException("timeout value is negative");
329 if (nanos < 0 || nanos > 999999) {
330 throw new IllegalArgumentException(
331 "nanosecond timeout value out of range");
334 if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
342 * Initializes a Thread.
344 * @param g the Thread group
345 * @param target the object whose run() method gets called
346 * @param name the name of the new Thread
347 * @param stackSize the desired stack size for the new thread, or
348 * zero to indicate that this parameter is to be ignored.
350 private void init(ThreadGroup g, Runnable target, String name,
353 throw new NullPointerException("name cannot be null");
356 Thread parent = currentThread();
357 SecurityManager security = System.getSecurityManager();
359 /* Determine if it's an applet or not */
361 /* If there is a security manager, ask the security manager
363 if (security != null) {
364 g = security.getThreadGroup();
367 /* If the security doesn't have a strong opinion of the matter
368 use the parent thread group. */
370 g = parent.getThreadGroup();
374 /* checkAccess regardless of whether or not threadgroup is
375 explicitly passed in. */
379 * Do we have the required permissions?
381 if (security != null) {
382 if (isCCLOverridden(getClass())) {
383 security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
390 this.daemon = parent.isDaemon();
391 this.priority = parent.getPriority();
392 this.name = name.toCharArray();
393 if (security == null || isCCLOverridden(parent.getClass()))
394 this.contextClassLoader = parent.getContextClassLoader();
396 this.contextClassLoader = parent.contextClassLoader;
397 this.inheritedAccessControlContext = AccessController.getContext();
398 this.target = target;
399 setPriority(priority);
400 if (parent.inheritableThreadLocals != null)
401 this.inheritableThreadLocals =
402 ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
403 /* Stash the specified stack size in case the VM cares */
404 this.stackSize = stackSize;
407 tid = nextThreadID();
411 * Throws CloneNotSupportedException as a Thread can not be meaningfully
412 * cloned. Construct a new Thread instead.
414 * @throws CloneNotSupportedException
418 protected Object clone() throws CloneNotSupportedException {
419 throw new CloneNotSupportedException();
423 * Allocates a new {@code Thread} object. This constructor has the same
424 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
425 * {@code (null, null, gname)}, where {@code gname} is a newly generated
426 * name. Automatically generated names are of the form
427 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
430 init(null, null, "Thread-" + nextThreadNum(), 0);
434 * Allocates a new {@code Thread} object. This constructor has the same
435 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
436 * {@code (null, target, gname)}, where {@code gname} is a newly generated
437 * name. Automatically generated names are of the form
438 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
441 * the object whose {@code run} method is invoked when this thread
442 * is started. If {@code null}, this classes {@code run} method does
445 public Thread(Runnable target) {
446 init(null, target, "Thread-" + nextThreadNum(), 0);
450 * Allocates a new {@code Thread} object. This constructor has the same
451 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
452 * {@code (group, target, gname)} ,where {@code gname} is a newly generated
453 * name. Automatically generated names are of the form
454 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
457 * the thread group. If {@code null} and there is a security
458 * manager, the group is determined by {@linkplain
459 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
460 * If there is not a security manager or {@code
461 * SecurityManager.getThreadGroup()} returns {@code null}, the group
462 * is set to the current thread's thread group.
465 * the object whose {@code run} method is invoked when this thread
466 * is started. If {@code null}, this thread's run method is invoked.
468 * @throws SecurityException
469 * if the current thread cannot create a thread in the specified
472 public Thread(ThreadGroup group, Runnable target) {
473 init(group, target, "Thread-" + nextThreadNum(), 0);
477 * Allocates a new {@code Thread} object. This constructor has the same
478 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
479 * {@code (null, null, name)}.
482 * the name of the new thread
484 public Thread(String name) {
485 init(null, null, name, 0);
489 * Allocates a new {@code Thread} object. This constructor has the same
490 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
491 * {@code (group, null, name)}.
494 * the thread group. If {@code null} and there is a security
495 * manager, the group is determined by {@linkplain
496 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
497 * If there is not a security manager or {@code
498 * SecurityManager.getThreadGroup()} returns {@code null}, the group
499 * is set to the current thread's thread group.
502 * the name of the new thread
504 * @throws SecurityException
505 * if the current thread cannot create a thread in the specified
508 public Thread(ThreadGroup group, String name) {
509 init(group, null, name, 0);
513 * Allocates a new {@code Thread} object. This constructor has the same
514 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
515 * {@code (null, target, name)}.
518 * the object whose {@code run} method is invoked when this thread
519 * is started. If {@code null}, this thread's run method is invoked.
522 * the name of the new thread
524 public Thread(Runnable target, String name) {
525 init(null, target, name, 0);
529 * Allocates a new {@code Thread} object so that it has {@code target}
530 * as its run object, has the specified {@code name} as its name,
531 * and belongs to the thread group referred to by {@code group}.
533 * <p>If there is a security manager, its
534 * {@link SecurityManager#checkAccess(ThreadGroup) checkAccess}
535 * method is invoked with the ThreadGroup as its argument.
537 * <p>In addition, its {@code checkPermission} method is invoked with
538 * the {@code RuntimePermission("enableContextClassLoaderOverride")}
539 * permission when invoked directly or indirectly by the constructor
540 * of a subclass which overrides the {@code getContextClassLoader}
541 * or {@code setContextClassLoader} methods.
543 * <p>The priority of the newly created thread is set equal to the
544 * priority of the thread creating it, that is, the currently running
545 * thread. The method {@linkplain #setPriority setPriority} may be
546 * used to change the priority to a new value.
548 * <p>The newly created thread is initially marked as being a daemon
549 * thread if and only if the thread creating it is currently marked
550 * as a daemon thread. The method {@linkplain #setDaemon setDaemon}
551 * may be used to change whether or not a thread is a daemon.
554 * the thread group. If {@code null} and there is a security
555 * manager, the group is determined by {@linkplain
556 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
557 * If there is not a security manager or {@code
558 * SecurityManager.getThreadGroup()} returns {@code null}, the group
559 * is set to the current thread's thread group.
562 * the object whose {@code run} method is invoked when this thread
563 * is started. If {@code null}, this thread's run method is invoked.
566 * the name of the new thread
568 * @throws SecurityException
569 * if the current thread cannot create a thread in the specified
570 * thread group or cannot override the context class loader methods.
572 public Thread(ThreadGroup group, Runnable target, String name) {
573 init(group, target, name, 0);
577 * Allocates a new {@code Thread} object so that it has {@code target}
578 * as its run object, has the specified {@code name} as its name,
579 * and belongs to the thread group referred to by {@code group}, and has
580 * the specified <i>stack size</i>.
582 * <p>This constructor is identical to {@link
583 * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact
584 * that it allows the thread stack size to be specified. The stack size
585 * is the approximate number of bytes of address space that the virtual
586 * machine is to allocate for this thread's stack. <b>The effect of the
587 * {@code stackSize} parameter, if any, is highly platform dependent.</b>
589 * <p>On some platforms, specifying a higher value for the
590 * {@code stackSize} parameter may allow a thread to achieve greater
591 * recursion depth before throwing a {@link StackOverflowError}.
592 * Similarly, specifying a lower value may allow a greater number of
593 * threads to exist concurrently without throwing an {@link
594 * OutOfMemoryError} (or other internal error). The details of
595 * the relationship between the value of the <tt>stackSize</tt> parameter
596 * and the maximum recursion depth and concurrency level are
597 * platform-dependent. <b>On some platforms, the value of the
598 * {@code stackSize} parameter may have no effect whatsoever.</b>
600 * <p>The virtual machine is free to treat the {@code stackSize}
601 * parameter as a suggestion. If the specified value is unreasonably low
602 * for the platform, the virtual machine may instead use some
603 * platform-specific minimum value; if the specified value is unreasonably
604 * high, the virtual machine may instead use some platform-specific
605 * maximum. Likewise, the virtual machine is free to round the specified
606 * value up or down as it sees fit (or to ignore it completely).
608 * <p>Specifying a value of zero for the {@code stackSize} parameter will
609 * cause this constructor to behave exactly like the
610 * {@code Thread(ThreadGroup, Runnable, String)} constructor.
612 * <p><i>Due to the platform-dependent nature of the behavior of this
613 * constructor, extreme care should be exercised in its use.
614 * The thread stack size necessary to perform a given computation will
615 * likely vary from one JRE implementation to another. In light of this
616 * variation, careful tuning of the stack size parameter may be required,
617 * and the tuning may need to be repeated for each JRE implementation on
618 * which an application is to run.</i>
620 * <p>Implementation note: Java platform implementers are encouraged to
621 * document their implementation's behavior with respect to the
622 * {@code stackSize} parameter.
626 * the thread group. If {@code null} and there is a security
627 * manager, the group is determined by {@linkplain
628 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
629 * If there is not a security manager or {@code
630 * SecurityManager.getThreadGroup()} returns {@code null}, the group
631 * is set to the current thread's thread group.
634 * the object whose {@code run} method is invoked when this thread
635 * is started. If {@code null}, this thread's run method is invoked.
638 * the name of the new thread
641 * the desired stack size for the new thread, or zero to indicate
642 * that this parameter is to be ignored.
644 * @throws SecurityException
645 * if the current thread cannot create a thread in the specified
650 public Thread(ThreadGroup group, Runnable target, String name,
652 init(group, target, name, stackSize);
656 * Causes this thread to begin execution; the Java Virtual Machine
657 * calls the <code>run</code> method of this thread.
659 * The result is that two threads are running concurrently: the
660 * current thread (which returns from the call to the
661 * <code>start</code> method) and the other thread (which executes its
662 * <code>run</code> method).
664 * It is never legal to start a thread more than once.
665 * In particular, a thread may not be restarted once it has completed
668 * @exception IllegalThreadStateException if the thread was already
673 public synchronized void start() {
675 * This method is not invoked for the main method thread or "system"
676 * group threads created/set up by the VM. Any new functionality added
677 * to this method in the future may have to also be added to the VM.
679 * A zero status value corresponds to state "NEW".
681 if (threadStatus != 0)
682 throw new IllegalThreadStateException();
684 /* Notify the group that this thread is about to be started
685 * so that it can be added to the group's list of threads
686 * and the group's unstarted count can be decremented. */
689 boolean started = false;
696 group.threadStartFailed(this);
698 } catch (Throwable ignore) {
699 /* do nothing. If start0 threw a Throwable then
700 it will be passed up the call stack */
705 private native void start0();
708 * If this thread was constructed using a separate
709 * <code>Runnable</code> run object, then that
710 * <code>Runnable</code> object's <code>run</code> method is called;
711 * otherwise, this method does nothing and returns.
713 * Subclasses of <code>Thread</code> should override this method.
717 * @see #Thread(ThreadGroup, Runnable, String)
721 if (target != null) {
727 * This method is called by the system to give a Thread
728 * a chance to clean up before it actually exits.
730 private void exit() {
732 group.threadTerminated(this);
735 /* Aggressively null out all reference fields: see bug 4006245 */
737 /* Speed the release of some of these resources */
739 inheritableThreadLocals = null;
740 inheritedAccessControlContext = null;
742 uncaughtExceptionHandler = null;
746 * Forces the thread to stop executing.
748 * If there is a security manager installed, its <code>checkAccess</code>
749 * method is called with <code>this</code>
750 * as its argument. This may result in a
751 * <code>SecurityException</code> being raised (in the current thread).
753 * If this thread is different from the current thread (that is, the current
754 * thread is trying to stop a thread other than itself), the
755 * security manager's <code>checkPermission</code> method (with a
756 * <code>RuntimePermission("stopThread")</code> argument) is called in
758 * Again, this may result in throwing a
759 * <code>SecurityException</code> (in the current thread).
761 * The thread represented by this thread is forced to stop whatever
762 * it is doing abnormally and to throw a newly created
763 * <code>ThreadDeath</code> object as an exception.
765 * It is permitted to stop a thread that has not yet been started.
766 * If the thread is eventually started, it immediately terminates.
768 * An application should not normally try to catch
769 * <code>ThreadDeath</code> unless it must do some extraordinary
770 * cleanup operation (note that the throwing of
771 * <code>ThreadDeath</code> causes <code>finally</code> clauses of
772 * <code>try</code> statements to be executed before the thread
773 * officially dies). If a <code>catch</code> clause catches a
774 * <code>ThreadDeath</code> object, it is important to rethrow the
775 * object so that the thread actually dies.
777 * The top-level error handler that reacts to otherwise uncaught
778 * exceptions does not print out a message or otherwise notify the
779 * application if the uncaught exception is an instance of
780 * <code>ThreadDeath</code>.
782 * @exception SecurityException if the current thread cannot
783 * modify this thread.
785 * @see #checkAccess()
789 * @see ThreadGroup#uncaughtException(Thread,Throwable)
790 * @see SecurityManager#checkAccess(Thread)
791 * @see SecurityManager#checkPermission
792 * @deprecated This method is inherently unsafe. Stopping a thread with
793 * Thread.stop causes it to unlock all of the monitors that it
794 * has locked (as a natural consequence of the unchecked
795 * <code>ThreadDeath</code> exception propagating up the stack). If
796 * any of the objects previously protected by these monitors were in
797 * an inconsistent state, the damaged objects become visible to
798 * other threads, potentially resulting in arbitrary behavior. Many
799 * uses of <code>stop</code> should be replaced by code that simply
800 * modifies some variable to indicate that the target thread should
801 * stop running. The target thread should check this variable
802 * regularly, and return from its run method in an orderly fashion
803 * if the variable indicates that it is to stop running. If the
804 * target thread waits for long periods (on a condition variable,
805 * for example), the <code>interrupt</code> method should be used to
806 * interrupt the wait.
807 * For more information, see
808 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
809 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
812 public final void stop() {
813 stop(new ThreadDeath());
817 * Forces the thread to stop executing.
819 * If there is a security manager installed, the <code>checkAccess</code>
820 * method of this thread is called, which may result in a
821 * <code>SecurityException</code> being raised (in the current thread).
823 * If this thread is different from the current thread (that is, the current
824 * thread is trying to stop a thread other than itself) or
825 * <code>obj</code> is not an instance of <code>ThreadDeath</code>, the
826 * security manager's <code>checkPermission</code> method (with the
827 * <code>RuntimePermission("stopThread")</code> argument) is called in
829 * Again, this may result in throwing a
830 * <code>SecurityException</code> (in the current thread).
832 * If the argument <code>obj</code> is null, a
833 * <code>NullPointerException</code> is thrown (in the current thread).
835 * The thread represented by this thread is forced to stop
836 * whatever it is doing abnormally and to throw the
837 * <code>Throwable</code> object <code>obj</code> as an exception. This
838 * is an unusual action to take; normally, the <code>stop</code> method
839 * that takes no arguments should be used.
841 * It is permitted to stop a thread that has not yet been started.
842 * If the thread is eventually started, it immediately terminates.
844 * @param obj the Throwable object to be thrown.
845 * @exception SecurityException if the current thread cannot modify
847 * @throws NullPointerException if obj is <tt>null</tt>.
849 * @see #checkAccess()
853 * @see SecurityManager#checkAccess(Thread)
854 * @see SecurityManager#checkPermission
855 * @deprecated This method is inherently unsafe. See {@link #stop()}
856 * for details. An additional danger of this
857 * method is that it may be used to generate exceptions that the
858 * target thread is unprepared to handle (including checked
859 * exceptions that the thread could not possibly throw, were it
860 * not for this method).
861 * For more information, see
862 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
863 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
866 public final synchronized void stop(Throwable obj) {
868 throw new NullPointerException();
870 SecurityManager security = System.getSecurityManager();
871 if (security != null) {
873 if ((this != Thread.currentThread()) ||
874 (!(obj instanceof ThreadDeath))) {
875 security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
878 // A zero status value corresponds to "NEW", it can't change to
879 // not-NEW because we hold the lock.
880 if (threadStatus != 0) {
881 resume(); // Wake up thread if it was suspended; no-op otherwise
884 // The VM can handle all thread states
889 * Interrupts this thread.
891 * <p> Unless the current thread is interrupting itself, which is
892 * always permitted, the {@link #checkAccess() checkAccess} method
893 * of this thread is invoked, which may cause a {@link
894 * SecurityException} to be thrown.
896 * <p> If this thread is blocked in an invocation of the {@link
897 * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
898 * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
899 * class, or of the {@link #join()}, {@link #join(long)}, {@link
900 * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
901 * methods of this class, then its interrupt status will be cleared and it
902 * will receive an {@link InterruptedException}.
904 * <p> If this thread is blocked in an I/O operation upon an {@link
905 * java.nio.channels.InterruptibleChannel </code>interruptible
906 * channel<code>} then the channel will be closed, the thread's interrupt
907 * status will be set, and the thread will receive a {@link
908 * java.nio.channels.ClosedByInterruptException}.
910 * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
911 * then the thread's interrupt status will be set and it will return
912 * immediately from the selection operation, possibly with a non-zero
913 * value, just as if the selector's {@link
914 * java.nio.channels.Selector#wakeup wakeup} method were invoked.
916 * <p> If none of the previous conditions hold then this thread's interrupt
917 * status will be set. </p>
919 * <p> Interrupting a thread that is not alive need not have any effect.
921 * @throws SecurityException
922 * if the current thread cannot modify this thread
927 public void interrupt() {
928 if (this != Thread.currentThread())
931 synchronized (blockerLock) {
932 Interruptible b = blocker;
934 interrupt0(); // Just to set the interrupt flag
943 * Tests whether the current thread has been interrupted. The
944 * <i>interrupted status</i> of the thread is cleared by this method. In
945 * other words, if this method were to be called twice in succession, the
946 * second call would return false (unless the current thread were
947 * interrupted again, after the first call had cleared its interrupted
948 * status and before the second call had examined it).
950 * <p>A thread interruption ignored because a thread was not alive
951 * at the time of the interrupt will be reflected by this method
954 * @return <code>true</code> if the current thread has been interrupted;
955 * <code>false</code> otherwise.
956 * @see #isInterrupted()
959 public static boolean interrupted() {
960 return currentThread().isInterrupted(true);
964 * Tests whether this thread has been interrupted. The <i>interrupted
965 * status</i> of the thread is unaffected by this method.
967 * <p>A thread interruption ignored because a thread was not alive
968 * at the time of the interrupt will be reflected by this method
971 * @return <code>true</code> if this thread has been interrupted;
972 * <code>false</code> otherwise.
973 * @see #interrupted()
976 public boolean isInterrupted() {
977 return isInterrupted(false);
981 * Tests if some Thread has been interrupted. The interrupted state
982 * is reset or not based on the value of ClearInterrupted that is
985 private native boolean isInterrupted(boolean ClearInterrupted);
988 * Throws {@link NoSuchMethodError}.
990 * @deprecated This method was originally designed to destroy this
991 * thread without any cleanup. Any monitors it held would have
992 * remained locked. However, the method was never implemented.
993 * If if were to be implemented, it would be deadlock-prone in
994 * much the manner of {@link #suspend}. If the target thread held
995 * a lock protecting a critical system resource when it was
996 * destroyed, no thread could ever access this resource again.
997 * If another thread ever attempted to lock this resource, deadlock
998 * would result. Such deadlocks typically manifest themselves as
999 * "frozen" processes. For more information, see
1000 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">
1001 * Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1002 * @throws NoSuchMethodError always
1005 public void destroy() {
1006 throw new NoSuchMethodError();
1010 * Tests if this thread is alive. A thread is alive if it has
1011 * been started and has not yet died.
1013 * @return <code>true</code> if this thread is alive;
1014 * <code>false</code> otherwise.
1016 public final native boolean isAlive();
1019 * Suspends this thread.
1021 * First, the <code>checkAccess</code> method of this thread is called
1022 * with no arguments. This may result in throwing a
1023 * <code>SecurityException </code>(in the current thread).
1025 * If the thread is alive, it is suspended and makes no further
1026 * progress unless and until it is resumed.
1028 * @exception SecurityException if the current thread cannot modify
1031 * @deprecated This method has been deprecated, as it is
1032 * inherently deadlock-prone. If the target thread holds a lock on the
1033 * monitor protecting a critical system resource when it is suspended, no
1034 * thread can access this resource until the target thread is resumed. If
1035 * the thread that would resume the target thread attempts to lock this
1036 * monitor prior to calling <code>resume</code>, deadlock results. Such
1037 * deadlocks typically manifest themselves as "frozen" processes.
1038 * For more information, see
1039 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
1040 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1043 public final void suspend() {
1049 * Resumes a suspended thread.
1051 * First, the <code>checkAccess</code> method of this thread is called
1052 * with no arguments. This may result in throwing a
1053 * <code>SecurityException</code> (in the current thread).
1055 * If the thread is alive but suspended, it is resumed and is
1056 * permitted to make progress in its execution.
1058 * @exception SecurityException if the current thread cannot modify this
1062 * @deprecated This method exists solely for use with {@link #suspend},
1063 * which has been deprecated because it is deadlock-prone.
1064 * For more information, see
1065 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
1066 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1069 public final void resume() {
1075 * Changes the priority of this thread.
1077 * First the <code>checkAccess</code> method of this thread is called
1078 * with no arguments. This may result in throwing a
1079 * <code>SecurityException</code>.
1081 * Otherwise, the priority of this thread is set to the smaller of
1082 * the specified <code>newPriority</code> and the maximum permitted
1083 * priority of the thread's thread group.
1085 * @param newPriority priority to set this thread to
1086 * @exception IllegalArgumentException If the priority is not in the
1087 * range <code>MIN_PRIORITY</code> to
1088 * <code>MAX_PRIORITY</code>.
1089 * @exception SecurityException if the current thread cannot modify
1092 * @see #checkAccess()
1093 * @see #getThreadGroup()
1094 * @see #MAX_PRIORITY
1095 * @see #MIN_PRIORITY
1096 * @see ThreadGroup#getMaxPriority()
1098 public final void setPriority(int newPriority) {
1101 if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
1102 throw new IllegalArgumentException();
1104 if((g = getThreadGroup()) != null) {
1105 if (newPriority > g.getMaxPriority()) {
1106 newPriority = g.getMaxPriority();
1108 setPriority0(priority = newPriority);
1113 * Returns this thread's priority.
1115 * @return this thread's priority.
1118 public final int getPriority() {
1123 * Changes the name of this thread to be equal to the argument
1124 * <code>name</code>.
1126 * First the <code>checkAccess</code> method of this thread is called
1127 * with no arguments. This may result in throwing a
1128 * <code>SecurityException</code>.
1130 * @param name the new name for this thread.
1131 * @exception SecurityException if the current thread cannot modify this
1134 * @see #checkAccess()
1136 public final void setName(String name) {
1138 this.name = name.toCharArray();
1142 * Returns this thread's name.
1144 * @return this thread's name.
1145 * @see #setName(String)
1147 public final String getName() {
1148 return String.valueOf(name);
1152 * Returns the thread group to which this thread belongs.
1153 * This method returns null if this thread has died
1156 * @return this thread's thread group.
1158 public final ThreadGroup getThreadGroup() {
1163 * Returns an estimate of the number of active threads in the current
1164 * thread's {@linkplain java.lang.ThreadGroup thread group} and its
1165 * subgroups. Recursively iterates over all subgroups in the current
1166 * thread's thread group.
1168 * <p> The value returned is only an estimate because the number of
1169 * threads may change dynamically while this method traverses internal
1170 * data structures, and might be affected by the presence of certain
1171 * system threads. This method is intended primarily for debugging
1172 * and monitoring purposes.
1174 * @return an estimate of the number of active threads in the current
1175 * thread's thread group and in any other thread group that
1176 * has the current thread's thread group as an ancestor
1178 public static int activeCount() {
1179 return currentThread().getThreadGroup().activeCount();
1183 * Copies into the specified array every active thread in the current
1184 * thread's thread group and its subgroups. This method simply
1185 * invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])}
1186 * method of the current thread's thread group.
1188 * <p> An application might use the {@linkplain #activeCount activeCount}
1189 * method to get an estimate of how big the array should be, however
1190 * <i>if the array is too short to hold all the threads, the extra threads
1191 * are silently ignored.</i> If it is critical to obtain every active
1192 * thread in the current thread's thread group and its subgroups, the
1193 * invoker should verify that the returned int value is strictly less
1194 * than the length of {@code tarray}.
1196 * <p> Due to the inherent race condition in this method, it is recommended
1197 * that the method only be used for debugging and monitoring purposes.
1200 * an array into which to put the list of threads
1202 * @return the number of threads put into the array
1204 * @throws SecurityException
1205 * if {@link java.lang.ThreadGroup#checkAccess} determines that
1206 * the current thread cannot access its thread group
1208 public static int enumerate(Thread tarray[]) {
1209 return currentThread().getThreadGroup().enumerate(tarray);
1213 * Counts the number of stack frames in this thread. The thread must
1216 * @return the number of stack frames in this thread.
1217 * @exception IllegalThreadStateException if this thread is not
1219 * @deprecated The definition of this call depends on {@link #suspend},
1220 * which is deprecated. Further, the results of this call
1221 * were never well-defined.
1224 public native int countStackFrames();
1227 * Waits at most {@code millis} milliseconds for this thread to
1228 * die. A timeout of {@code 0} means to wait forever.
1230 * <p> This implementation uses a loop of {@code this.wait} calls
1231 * conditioned on {@code this.isAlive}. As a thread terminates the
1232 * {@code this.notifyAll} method is invoked. It is recommended that
1233 * applications not use {@code wait}, {@code notify}, or
1234 * {@code notifyAll} on {@code Thread} instances.
1237 * the time to wait in milliseconds
1239 * @throws IllegalArgumentException
1240 * if the value of {@code millis} is negative
1242 * @throws InterruptedException
1243 * if any thread has interrupted the current thread. The
1244 * <i>interrupted status</i> of the current thread is
1245 * cleared when this exception is thrown.
1247 public final synchronized void join(long millis)
1248 throws InterruptedException {
1249 long base = System.currentTimeMillis();
1253 throw new IllegalArgumentException("timeout value is negative");
1262 long delay = millis - now;
1267 now = System.currentTimeMillis() - base;
1273 * Waits at most {@code millis} milliseconds plus
1274 * {@code nanos} nanoseconds for this thread to die.
1276 * <p> This implementation uses a loop of {@code this.wait} calls
1277 * conditioned on {@code this.isAlive}. As a thread terminates the
1278 * {@code this.notifyAll} method is invoked. It is recommended that
1279 * applications not use {@code wait}, {@code notify}, or
1280 * {@code notifyAll} on {@code Thread} instances.
1283 * the time to wait in milliseconds
1286 * {@code 0-999999} additional nanoseconds to wait
1288 * @throws IllegalArgumentException
1289 * if the value of {@code millis} is negative, or the value
1290 * of {@code nanos} is not in the range {@code 0-999999}
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.
1297 public final synchronized void join(long millis, int nanos)
1298 throws InterruptedException {
1301 throw new IllegalArgumentException("timeout value is negative");
1304 if (nanos < 0 || nanos > 999999) {
1305 throw new IllegalArgumentException(
1306 "nanosecond timeout value out of range");
1309 if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
1317 * Waits for this thread to die.
1319 * <p> An invocation of this method behaves in exactly the same
1320 * way as the invocation
1323 * {@linkplain #join(long) join}{@code (0)}
1326 * @throws InterruptedException
1327 * if any thread has interrupted the current thread. The
1328 * <i>interrupted status</i> of the current thread is
1329 * cleared when this exception is thrown.
1331 public final void join() throws InterruptedException {
1336 * Prints a stack trace of the current thread to the standard error stream.
1337 * This method is used only for debugging.
1339 * @see Throwable#printStackTrace()
1341 public static void dumpStack() {
1342 new Exception("Stack trace").printStackTrace();
1346 * Marks this thread as either a {@linkplain #isDaemon daemon} thread
1347 * or a user thread. The Java Virtual Machine exits when the only
1348 * threads running are all daemon threads.
1350 * <p> This method must be invoked before the thread is started.
1353 * if {@code true}, marks this thread as a daemon thread
1355 * @throws IllegalThreadStateException
1356 * if this thread is {@linkplain #isAlive alive}
1358 * @throws SecurityException
1359 * if {@link #checkAccess} determines that the current
1360 * thread cannot modify this thread
1362 public final void setDaemon(boolean on) {
1365 throw new IllegalThreadStateException();
1371 * Tests if this thread is a daemon thread.
1373 * @return <code>true</code> if this thread is a daemon thread;
1374 * <code>false</code> otherwise.
1375 * @see #setDaemon(boolean)
1377 public final boolean isDaemon() {
1382 * Determines if the currently running thread has permission to
1383 * modify this thread.
1385 * If there is a security manager, its <code>checkAccess</code> method
1386 * is called with this thread as its argument. This may result in
1387 * throwing a <code>SecurityException</code>.
1389 * @exception SecurityException if the current thread is not allowed to
1390 * access this thread.
1391 * @see SecurityManager#checkAccess(Thread)
1393 public final void checkAccess() {
1394 SecurityManager security = System.getSecurityManager();
1395 if (security != null) {
1396 security.checkAccess(this);
1401 * Returns a string representation of this thread, including the
1402 * thread's name, priority, and thread group.
1404 * @return a string representation of this thread.
1406 public String toString() {
1407 ThreadGroup group = getThreadGroup();
1408 if (group != null) {
1409 return "Thread[" + getName() + "," + getPriority() + "," +
1410 group.getName() + "]";
1412 return "Thread[" + getName() + "," + getPriority() + "," +
1418 * Returns the context ClassLoader for this Thread. The context
1419 * ClassLoader is provided by the creator of the thread for use
1420 * by code running in this thread when loading classes and resources.
1421 * If not {@linkplain #setContextClassLoader set}, the default is the
1422 * ClassLoader context of the parent Thread. The context ClassLoader of the
1423 * primordial thread is typically set to the class loader used to load the
1426 * <p>If a security manager is present, and the invoker's class loader is not
1427 * {@code null} and is not the same as or an ancestor of the context class
1428 * loader, then this method invokes the security manager's {@link
1429 * SecurityManager#checkPermission(java.security.Permission) checkPermission}
1430 * method with a {@link RuntimePermission RuntimePermission}{@code
1431 * ("getClassLoader")} permission to verify that retrieval of the context
1432 * class loader is permitted.
1434 * @return the context ClassLoader for this Thread, or {@code null}
1435 * indicating the system class loader (or, failing that, the
1436 * bootstrap class loader)
1438 * @throws SecurityException
1439 * if the current thread cannot get the context ClassLoader
1443 public ClassLoader getContextClassLoader() {
1444 if (contextClassLoader == null)
1446 SecurityManager sm = System.getSecurityManager();
1448 ClassLoader ccl = ClassLoader.getCallerClassLoader();
1449 if (ccl != null && ccl != contextClassLoader &&
1450 !contextClassLoader.isAncestor(ccl)) {
1451 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
1454 return contextClassLoader;
1458 * Sets the context ClassLoader for this Thread. The context
1459 * ClassLoader can be set when a thread is created, and allows
1460 * the creator of the thread to provide the appropriate class loader,
1461 * through {@code getContextClassLoader}, to code running in the thread
1462 * when loading classes and resources.
1464 * <p>If a security manager is present, its {@link
1465 * SecurityManager#checkPermission(java.security.Permission) checkPermission}
1466 * method is invoked with a {@link RuntimePermission RuntimePermission}{@code
1467 * ("setContextClassLoader")} permission to see if setting the context
1468 * ClassLoader is permitted.
1471 * the context ClassLoader for this Thread, or null indicating the
1472 * system class loader (or, failing that, the bootstrap class loader)
1474 * @throws SecurityException
1475 * if the current thread cannot set the context ClassLoader
1479 public void setContextClassLoader(ClassLoader cl) {
1480 SecurityManager sm = System.getSecurityManager();
1482 sm.checkPermission(new RuntimePermission("setContextClassLoader"));
1484 contextClassLoader = cl;
1488 * Returns <tt>true</tt> if and only if the current thread holds the
1489 * monitor lock on the specified object.
1491 * <p>This method is designed to allow a program to assert that
1492 * the current thread already holds a specified lock:
1494 * assert Thread.holdsLock(obj);
1497 * @param obj the object on which to test lock ownership
1498 * @throws NullPointerException if obj is <tt>null</tt>
1499 * @return <tt>true</tt> if the current thread holds the monitor lock on
1500 * the specified object.
1503 public static native boolean holdsLock(Object obj);
1505 private static final StackTraceElement[] EMPTY_STACK_TRACE
1506 = new StackTraceElement[0];
1509 * Returns an array of stack trace elements representing the stack dump
1510 * of this thread. This method will return a zero-length array if
1511 * this thread has not started, has started but has not yet been
1512 * scheduled to run by the system, or has terminated.
1513 * If the returned array is of non-zero length then the first element of
1514 * the array represents the top of the stack, which is the most recent
1515 * method invocation in the sequence. The last element of the array
1516 * represents the bottom of the stack, which is the least recent method
1517 * invocation in the sequence.
1519 * <p>If there is a security manager, and this thread is not
1520 * the current thread, then the security manager's
1521 * <tt>checkPermission</tt> method is called with a
1522 * <tt>RuntimePermission("getStackTrace")</tt> permission
1523 * to see if it's ok to get the stack trace.
1525 * <p>Some virtual machines may, under some circumstances, omit one
1526 * or more stack frames from the stack trace. In the extreme case,
1527 * a virtual machine that has no stack trace information concerning
1528 * this thread is permitted to return a zero-length array from this
1531 * @return an array of <tt>StackTraceElement</tt>,
1532 * each represents one stack frame.
1534 * @throws SecurityException
1535 * if a security manager exists and its
1536 * <tt>checkPermission</tt> method doesn't allow
1537 * getting the stack trace of thread.
1538 * @see SecurityManager#checkPermission
1539 * @see RuntimePermission
1540 * @see Throwable#getStackTrace
1544 public StackTraceElement[] getStackTrace() {
1545 if (this != Thread.currentThread()) {
1546 // check for getStackTrace permission
1547 SecurityManager security = System.getSecurityManager();
1548 if (security != null) {
1549 security.checkPermission(
1550 SecurityConstants.GET_STACK_TRACE_PERMISSION);
1552 // optimization so we do not call into the vm for threads that
1553 // have not yet started or have terminated
1555 return EMPTY_STACK_TRACE;
1557 StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
1558 StackTraceElement[] stackTrace = stackTraceArray[0];
1559 // a thread that was alive during the previous isAlive call may have
1560 // since terminated, therefore not having a stacktrace.
1561 if (stackTrace == null) {
1562 stackTrace = EMPTY_STACK_TRACE;
1566 // Don't need JVM help for current thread
1567 return (new Exception()).getStackTrace();
1572 * Returns a map of stack traces for all live threads.
1573 * The map keys are threads and each map value is an array of
1574 * <tt>StackTraceElement</tt> that represents the stack dump
1575 * of the corresponding <tt>Thread</tt>.
1576 * The returned stack traces are in the format specified for
1577 * the {@link #getStackTrace getStackTrace} method.
1579 * <p>The threads may be executing while this method is called.
1580 * The stack trace of each thread only represents a snapshot and
1581 * each stack trace may be obtained at different time. A zero-length
1582 * array will be returned in the map value if the virtual machine has
1583 * no stack trace information about a thread.
1585 * <p>If there is a security manager, then the security manager's
1586 * <tt>checkPermission</tt> method is called with a
1587 * <tt>RuntimePermission("getStackTrace")</tt> permission as well as
1588 * <tt>RuntimePermission("modifyThreadGroup")</tt> permission
1589 * to see if it is ok to get the stack trace of all threads.
1591 * @return a <tt>Map</tt> from <tt>Thread</tt> to an array of
1592 * <tt>StackTraceElement</tt> that represents the stack trace of
1593 * the corresponding thread.
1595 * @throws SecurityException
1596 * if a security manager exists and its
1597 * <tt>checkPermission</tt> method doesn't allow
1598 * getting the stack trace of thread.
1599 * @see #getStackTrace
1600 * @see SecurityManager#checkPermission
1601 * @see RuntimePermission
1602 * @see Throwable#getStackTrace
1606 public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
1607 // check for getStackTrace permission
1608 SecurityManager security = System.getSecurityManager();
1609 if (security != null) {
1610 security.checkPermission(
1611 SecurityConstants.GET_STACK_TRACE_PERMISSION);
1612 security.checkPermission(
1613 SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
1616 // Get a snapshot of the list of all threads
1617 Thread[] threads = getThreads();
1618 StackTraceElement[][] traces = dumpThreads(threads);
1619 Map<Thread, StackTraceElement[]> m = new HashMap<>(threads.length);
1620 for (int i = 0; i < threads.length; i++) {
1621 StackTraceElement[] stackTrace = traces[i];
1622 if (stackTrace != null) {
1623 m.put(threads[i], stackTrace);
1625 // else terminated so we don't put it in the map
1631 private static final RuntimePermission SUBCLASS_IMPLEMENTATION_PERMISSION =
1632 new RuntimePermission("enableContextClassLoaderOverride");
1634 /** cache of subclass security audit results */
1635 /* Replace with ConcurrentReferenceHashMap when/if it appears in a future
1637 private static class Caches {
1638 /** cache of subclass security audit results */
1639 static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
1640 new ConcurrentHashMap<>();
1642 /** queue for WeakReferences to audited subclasses */
1643 static final ReferenceQueue<Class<?>> subclassAuditsQueue =
1644 new ReferenceQueue<>();
1648 * Verifies that this (possibly subclass) instance can be constructed
1649 * without violating security constraints: the subclass must not override
1650 * security-sensitive non-final methods, or else the
1651 * "enableContextClassLoaderOverride" RuntimePermission is checked.
1653 private static boolean isCCLOverridden(Class cl) {
1654 if (cl == Thread.class)
1657 processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
1658 WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
1659 Boolean result = Caches.subclassAudits.get(key);
1660 if (result == null) {
1661 result = Boolean.valueOf(auditSubclass(cl));
1662 Caches.subclassAudits.putIfAbsent(key, result);
1665 return result.booleanValue();
1669 * Performs reflective checks on given subclass to verify that it doesn't
1670 * override security-sensitive non-final methods. Returns true if the
1671 * subclass overrides any of the methods, false otherwise.
1673 private static boolean auditSubclass(final Class subcl) {
1674 Boolean result = AccessController.doPrivileged(
1675 new PrivilegedAction<Boolean>() {
1676 public Boolean run() {
1677 for (Class cl = subcl;
1679 cl = cl.getSuperclass())
1682 cl.getDeclaredMethod("getContextClassLoader", new Class[0]);
1683 return Boolean.TRUE;
1684 } catch (NoSuchMethodException ex) {
1687 Class[] params = {ClassLoader.class};
1688 cl.getDeclaredMethod("setContextClassLoader", params);
1689 return Boolean.TRUE;
1690 } catch (NoSuchMethodException ex) {
1693 return Boolean.FALSE;
1697 return result.booleanValue();
1700 private native static StackTraceElement[][] dumpThreads(Thread[] threads);
1701 private native static Thread[] getThreads();
1704 * Returns the identifier of this Thread. The thread ID is a positive
1705 * <tt>long</tt> number generated when this thread was created.
1706 * The thread ID is unique and remains unchanged during its lifetime.
1707 * When a thread is terminated, this thread ID may be reused.
1709 * @return this thread's ID.
1712 public long getId() {
1717 * A thread state. A thread can be in one of the following states:
1719 * <li>{@link #NEW}<br>
1720 * A thread that has not yet started is in this state.
1722 * <li>{@link #RUNNABLE}<br>
1723 * A thread executing in the Java virtual machine is in this state.
1725 * <li>{@link #BLOCKED}<br>
1726 * A thread that is blocked waiting for a monitor lock
1729 * <li>{@link #WAITING}<br>
1730 * A thread that is waiting indefinitely for another thread to
1731 * perform a particular action is in this state.
1733 * <li>{@link #TIMED_WAITING}<br>
1734 * A thread that is waiting for another thread to perform an action
1735 * for up to a specified waiting time is in this state.
1737 * <li>{@link #TERMINATED}<br>
1738 * A thread that has exited is in this state.
1743 * A thread can be in only one state at a given point in time.
1744 * These states are virtual machine states which do not reflect
1745 * any operating system thread states.
1752 * Thread state for a thread which has not yet started.
1757 * Thread state for a runnable thread. A thread in the runnable
1758 * state is executing in the Java virtual machine but it may
1759 * be waiting for other resources from the operating system
1760 * such as processor.
1765 * Thread state for a thread blocked waiting for a monitor lock.
1766 * A thread in the blocked state is waiting for a monitor lock
1767 * to enter a synchronized block/method or
1768 * reenter a synchronized block/method after calling
1769 * {@link Object#wait() Object.wait}.
1774 * Thread state for a waiting thread.
1775 * A thread is in the waiting state due to calling one of the
1776 * following methods:
1778 * <li>{@link Object#wait() Object.wait} with no timeout</li>
1779 * <li>{@link #join() Thread.join} with no timeout</li>
1780 * <li>{@link LockSupport#park() LockSupport.park}</li>
1783 * <p>A thread in the waiting state is waiting for another thread to
1784 * perform a particular action.
1786 * For example, a thread that has called <tt>Object.wait()</tt>
1787 * on an object is waiting for another thread to call
1788 * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
1789 * that object. A thread that has called <tt>Thread.join()</tt>
1790 * is waiting for a specified thread to terminate.
1795 * Thread state for a waiting thread with a specified waiting time.
1796 * A thread is in the timed waiting state due to calling one of
1797 * the following methods with a specified positive waiting time:
1799 * <li>{@link #sleep Thread.sleep}</li>
1800 * <li>{@link Object#wait(long) Object.wait} with timeout</li>
1801 * <li>{@link #join(long) Thread.join} with timeout</li>
1802 * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
1803 * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
1809 * Thread state for a terminated thread.
1810 * The thread has completed execution.
1816 * Returns the state of this thread.
1817 * This method is designed for use in monitoring of the system state,
1818 * not for synchronization control.
1820 * @return this thread's state.
1823 public State getState() {
1824 // get current thread state
1825 return sun.misc.VM.toThreadState(threadStatus);
1831 * Interface for handlers invoked when a <tt>Thread</tt> abruptly
1832 * terminates due to an uncaught exception.
1833 * <p>When a thread is about to terminate due to an uncaught exception
1834 * the Java Virtual Machine will query the thread for its
1835 * <tt>UncaughtExceptionHandler</tt> using
1836 * {@link #getUncaughtExceptionHandler} and will invoke the handler's
1837 * <tt>uncaughtException</tt> method, passing the thread and the
1838 * exception as arguments.
1839 * If a thread has not had its <tt>UncaughtExceptionHandler</tt>
1840 * explicitly set, then its <tt>ThreadGroup</tt> object acts as its
1841 * <tt>UncaughtExceptionHandler</tt>. If the <tt>ThreadGroup</tt> object
1843 * special requirements for dealing with the exception, it can forward
1844 * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
1845 * default uncaught exception handler}.
1847 * @see #setDefaultUncaughtExceptionHandler
1848 * @see #setUncaughtExceptionHandler
1849 * @see ThreadGroup#uncaughtException
1852 public interface UncaughtExceptionHandler {
1854 * Method invoked when the given thread terminates due to the
1855 * given uncaught exception.
1856 * <p>Any exception thrown by this method will be ignored by the
1857 * Java Virtual Machine.
1858 * @param t the thread
1859 * @param e the exception
1861 void uncaughtException(Thread t, Throwable e);
1864 // null unless explicitly set
1865 private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
1867 // null unless explicitly set
1868 private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
1871 * Set the default handler invoked when a thread abruptly terminates
1872 * due to an uncaught exception, and no other handler has been defined
1875 * <p>Uncaught exception handling is controlled first by the thread, then
1876 * by the thread's {@link ThreadGroup} object and finally by the default
1877 * uncaught exception handler. If the thread does not have an explicit
1878 * uncaught exception handler set, and the thread's thread group
1879 * (including parent thread groups) does not specialize its
1880 * <tt>uncaughtException</tt> method, then the default handler's
1881 * <tt>uncaughtException</tt> method will be invoked.
1882 * <p>By setting the default uncaught exception handler, an application
1883 * can change the way in which uncaught exceptions are handled (such as
1884 * logging to a specific device, or file) for those threads that would
1885 * already accept whatever "default" behavior the system
1888 * <p>Note that the default uncaught exception handler should not usually
1889 * defer to the thread's <tt>ThreadGroup</tt> object, as that could cause
1890 * infinite recursion.
1892 * @param eh the object to use as the default uncaught exception handler.
1893 * If <tt>null</tt> then there is no default handler.
1895 * @throws SecurityException if a security manager is present and it
1896 * denies <tt>{@link RuntimePermission}
1897 * ("setDefaultUncaughtExceptionHandler")</tt>
1899 * @see #setUncaughtExceptionHandler
1900 * @see #getUncaughtExceptionHandler
1901 * @see ThreadGroup#uncaughtException
1904 public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
1905 SecurityManager sm = System.getSecurityManager();
1908 new RuntimePermission("setDefaultUncaughtExceptionHandler")
1912 defaultUncaughtExceptionHandler = eh;
1916 * Returns the default handler invoked when a thread abruptly terminates
1917 * due to an uncaught exception. If the returned value is <tt>null</tt>,
1918 * there is no default.
1920 * @see #setDefaultUncaughtExceptionHandler
1922 public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
1923 return defaultUncaughtExceptionHandler;
1927 * Returns the handler invoked when this thread abruptly terminates
1928 * due to an uncaught exception. If this thread has not had an
1929 * uncaught exception handler explicitly set then this thread's
1930 * <tt>ThreadGroup</tt> object is returned, unless this thread
1931 * has terminated, in which case <tt>null</tt> is returned.
1934 public UncaughtExceptionHandler getUncaughtExceptionHandler() {
1935 return uncaughtExceptionHandler != null ?
1936 uncaughtExceptionHandler : group;
1940 * Set the handler invoked when this thread abruptly terminates
1941 * due to an uncaught exception.
1942 * <p>A thread can take full control of how it responds to uncaught
1943 * exceptions by having its uncaught exception handler explicitly set.
1944 * If no such handler is set then the thread's <tt>ThreadGroup</tt>
1945 * object acts as its handler.
1946 * @param eh the object to use as this thread's uncaught exception
1947 * handler. If <tt>null</tt> then this thread has no explicit handler.
1948 * @throws SecurityException if the current thread is not allowed to
1949 * modify this thread.
1950 * @see #setDefaultUncaughtExceptionHandler
1951 * @see ThreadGroup#uncaughtException
1954 public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
1956 uncaughtExceptionHandler = eh;
1960 * Dispatch an uncaught exception to the handler. This method is
1961 * intended to be called only by the JVM.
1963 private void dispatchUncaughtException(Throwable e) {
1964 getUncaughtExceptionHandler().uncaughtException(this, e);
1968 * Removes from the specified map any keys that have been enqueued
1969 * on the specified reference queue.
1971 static void processQueue(ReferenceQueue<Class<?>> queue,
1972 ConcurrentMap<? extends
1973 WeakReference<Class<?>>, ?> map)
1975 Reference<? extends Class<?>> ref;
1976 while((ref = queue.poll()) != null) {
1982 * Weak key for Class objects.
1984 static class WeakClassKey extends WeakReference<Class<?>> {
1986 * saved value of the referent's identity hash code, to maintain
1987 * a consistent hash code after the referent has been cleared
1989 private final int hash;
1992 * Create a new WeakClassKey to the given object, registered
1995 WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) {
1996 super(cl, refQueue);
1997 hash = System.identityHashCode(cl);
2001 * Returns the identity hash code of the original referent.
2004 public int hashCode() {
2009 * Returns true if the given object is this identical
2010 * WeakClassKey instance, or, if this object's referent has not
2011 * been cleared, if the given object is another WeakClassKey
2012 * instance with the identical non-null referent as this one.
2015 public boolean equals(Object obj) {
2019 if (obj instanceof WeakClassKey) {
2020 Object referent = get();
2021 return (referent != null) &&
2022 (referent == ((WeakClassKey) obj).get());
2029 /* Some private helper methods */
2030 private native void setPriority0(int newPriority);
2031 private native void stop0(Object o);
2032 private native void suspend0();
2033 private native void resume0();
2034 private native void interrupt0();