0N/A/*
3909N/A * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage java.lang;
0N/A
905N/Aimport java.lang.ref.Reference;
905N/Aimport java.lang.ref.ReferenceQueue;
905N/Aimport java.lang.ref.WeakReference;
0N/Aimport java.security.AccessController;
0N/Aimport java.security.AccessControlContext;
0N/Aimport java.security.PrivilegedAction;
0N/Aimport java.util.Map;
0N/Aimport java.util.HashMap;
905N/Aimport java.util.concurrent.ConcurrentHashMap;
905N/Aimport java.util.concurrent.ConcurrentMap;
0N/Aimport java.util.concurrent.locks.LockSupport;
0N/Aimport sun.nio.ch.Interruptible;
6338N/Aimport sun.reflect.CallerSensitive;
6338N/Aimport sun.reflect.Reflection;
0N/Aimport sun.security.util.SecurityConstants;
0N/A
0N/A
0N/A/**
0N/A * A <i>thread</i> is a thread of execution in a program. The Java
0N/A * Virtual Machine allows an application to have multiple threads of
0N/A * execution running concurrently.
0N/A * <p>
0N/A * Every thread has a priority. Threads with higher priority are
0N/A * executed in preference to threads with lower priority. Each thread
0N/A * may or may not also be marked as a daemon. When code running in
0N/A * some thread creates a new <code>Thread</code> object, the new
0N/A * thread has its priority initially set equal to the priority of the
0N/A * creating thread, and is a daemon thread if and only if the
0N/A * creating thread is a daemon.
0N/A * <p>
0N/A * When a Java Virtual Machine starts up, there is usually a single
0N/A * non-daemon thread (which typically calls the method named
0N/A * <code>main</code> of some designated class). The Java Virtual
0N/A * Machine continues to execute threads until either of the following
0N/A * occurs:
0N/A * <ul>
0N/A * <li>The <code>exit</code> method of class <code>Runtime</code> has been
0N/A * called and the security manager has permitted the exit operation
0N/A * to take place.
0N/A * <li>All threads that are not daemon threads have died, either by
0N/A * returning from the call to the <code>run</code> method or by
0N/A * throwing an exception that propagates beyond the <code>run</code>
0N/A * method.
0N/A * </ul>
0N/A * <p>
0N/A * There are two ways to create a new thread of execution. One is to
0N/A * declare a class to be a subclass of <code>Thread</code>. This
0N/A * subclass should override the <code>run</code> method of class
0N/A * <code>Thread</code>. An instance of the subclass can then be
0N/A * allocated and started. For example, a thread that computes primes
0N/A * larger than a stated value could be written as follows:
0N/A * <p><hr><blockquote><pre>
0N/A * class PrimeThread extends Thread {
0N/A * long minPrime;
0N/A * PrimeThread(long minPrime) {
0N/A * this.minPrime = minPrime;
0N/A * }
0N/A *
0N/A * public void run() {
0N/A * // compute primes larger than minPrime
0N/A * &nbsp;.&nbsp;.&nbsp;.
0N/A * }
0N/A * }
0N/A * </pre></blockquote><hr>
0N/A * <p>
0N/A * The following code would then create a thread and start it running:
0N/A * <p><blockquote><pre>
0N/A * PrimeThread p = new PrimeThread(143);
0N/A * p.start();
0N/A * </pre></blockquote>
0N/A * <p>
0N/A * The other way to create a thread is to declare a class that
0N/A * implements the <code>Runnable</code> interface. That class then
0N/A * implements the <code>run</code> method. An instance of the class can
0N/A * then be allocated, passed as an argument when creating
0N/A * <code>Thread</code>, and started. The same example in this other
0N/A * style looks like the following:
0N/A * <p><hr><blockquote><pre>
0N/A * class PrimeRun implements Runnable {
0N/A * long minPrime;
0N/A * PrimeRun(long minPrime) {
0N/A * this.minPrime = minPrime;
0N/A * }
0N/A *
0N/A * public void run() {
0N/A * // compute primes larger than minPrime
0N/A * &nbsp;.&nbsp;.&nbsp;.
0N/A * }
0N/A * }
0N/A * </pre></blockquote><hr>
0N/A * <p>
0N/A * The following code would then create a thread and start it running:
0N/A * <p><blockquote><pre>
0N/A * PrimeRun p = new PrimeRun(143);
0N/A * new Thread(p).start();
0N/A * </pre></blockquote>
0N/A * <p>
0N/A * Every thread has a name for identification purposes. More than
0N/A * one thread may have the same name. If a name is not specified when
0N/A * a thread is created, a new name is generated for it.
520N/A * <p>
520N/A * Unless otherwise noted, passing a {@code null} argument to a constructor
520N/A * or method in this class will cause a {@link NullPointerException} to be
520N/A * thrown.
0N/A *
0N/A * @author unascribed
0N/A * @see Runnable
0N/A * @see Runtime#exit(int)
0N/A * @see #run()
0N/A * @see #stop()
0N/A * @since JDK1.0
0N/A */
0N/Apublic
0N/Aclass Thread implements Runnable {
0N/A /* Make sure registerNatives is the first thing <clinit> does. */
0N/A private static native void registerNatives();
0N/A static {
0N/A registerNatives();
0N/A }
0N/A
0N/A private char name[];
0N/A private int priority;
0N/A private Thread threadQ;
0N/A private long eetop;
0N/A
0N/A /* Whether or not to single_step this thread. */
0N/A private boolean single_step;
0N/A
0N/A /* Whether or not the thread is a daemon thread. */
0N/A private boolean daemon = false;
0N/A
0N/A /* JVM state */
0N/A private boolean stillborn = false;
0N/A
0N/A /* What will be run. */
0N/A private Runnable target;
0N/A
0N/A /* The group of this thread */
0N/A private ThreadGroup group;
0N/A
0N/A /* The context ClassLoader for this thread */
0N/A private ClassLoader contextClassLoader;
0N/A
0N/A /* The inherited AccessControlContext of this thread */
0N/A private AccessControlContext inheritedAccessControlContext;
0N/A
0N/A /* For autonumbering anonymous threads. */
0N/A private static int threadInitNumber;
0N/A private static synchronized int nextThreadNum() {
0N/A return threadInitNumber++;
0N/A }
0N/A
0N/A /* ThreadLocal values pertaining to this thread. This map is maintained
0N/A * by the ThreadLocal class. */
0N/A ThreadLocal.ThreadLocalMap threadLocals = null;
0N/A
0N/A /*
0N/A * InheritableThreadLocal values pertaining to this thread. This map is
0N/A * maintained by the InheritableThreadLocal class.
0N/A */
0N/A ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
0N/A
0N/A /*
0N/A * The requested stack size for this thread, or 0 if the creator did
0N/A * not specify a stack size. It is up to the VM to do whatever it
0N/A * likes with this number; some VMs will ignore it.
0N/A */
0N/A private long stackSize;
0N/A
0N/A /*
0N/A * JVM-private state that persists after native thread termination.
0N/A */
0N/A private long nativeParkEventPointer;
0N/A
0N/A /*
0N/A * Thread ID
0N/A */
0N/A private long tid;
0N/A
0N/A /* For generating thread ID */
0N/A private static long threadSeqNumber;
0N/A
0N/A /* Java thread status for tools,
0N/A * initialized to indicate thread 'not yet started'
0N/A */
0N/A
3225N/A private volatile int threadStatus = 0;
0N/A
0N/A
0N/A private static synchronized long nextThreadID() {
0N/A return ++threadSeqNumber;
0N/A }
0N/A
0N/A /**
0N/A * The argument supplied to the current call to
0N/A * java.util.concurrent.locks.LockSupport.park.
0N/A * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
0N/A * Accessed using java.util.concurrent.locks.LockSupport.getBlocker
0N/A */
0N/A volatile Object parkBlocker;
0N/A
0N/A /* The object in which this thread is blocked in an interruptible I/O
0N/A * operation, if any. The blocker's interrupt method should be invoked
0N/A * after setting this thread's interrupt status.
0N/A */
0N/A private volatile Interruptible blocker;
3037N/A private final Object blockerLock = new Object();
0N/A
0N/A /* Set the blocker field; invoked via sun.misc.SharedSecrets from java.nio code
0N/A */
0N/A void blockedOn(Interruptible b) {
0N/A synchronized (blockerLock) {
0N/A blocker = b;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * The minimum priority that a thread can have.
0N/A */
0N/A public final static int MIN_PRIORITY = 1;
0N/A
0N/A /**
0N/A * The default priority that is assigned to a thread.
0N/A */
0N/A public final static int NORM_PRIORITY = 5;
0N/A
0N/A /**
0N/A * The maximum priority that a thread can have.
0N/A */
0N/A public final static int MAX_PRIORITY = 10;
0N/A
0N/A /**
0N/A * Returns a reference to the currently executing thread object.
0N/A *
0N/A * @return the currently executing thread.
0N/A */
0N/A public static native Thread currentThread();
0N/A
0N/A /**
0N/A * A hint to the scheduler that the current thread is willing to yield
0N/A * its current use of a processor. The scheduler is free to ignore this
0N/A * hint.
0N/A *
0N/A * <p> Yield is a heuristic attempt to improve relative progression
0N/A * between threads that would otherwise over-utilise a CPU. Its use
0N/A * should be combined with detailed profiling and benchmarking to
0N/A * ensure that it actually has the desired effect.
0N/A *
0N/A * <p> It is rarely appropriate to use this method. It may be useful
0N/A * for debugging or testing purposes, where it may help to reproduce
0N/A * bugs due to race conditions. It may also be useful when designing
0N/A * concurrency control constructs such as the ones in the
0N/A * {@link java.util.concurrent.locks} package.
0N/A */
0N/A public static native void yield();
0N/A
0N/A /**
0N/A * Causes the currently executing thread to sleep (temporarily cease
0N/A * execution) for the specified number of milliseconds, subject to
0N/A * the precision and accuracy of system timers and schedulers. The thread
0N/A * does not lose ownership of any monitors.
0N/A *
0N/A * @param millis
0N/A * the length of time to sleep in milliseconds
0N/A *
0N/A * @throws IllegalArgumentException
0N/A * if the value of {@code millis} is negative
0N/A *
0N/A * @throws InterruptedException
0N/A * if any thread has interrupted the current thread. The
0N/A * <i>interrupted status</i> of the current thread is
0N/A * cleared when this exception is thrown.
0N/A */
0N/A public static native void sleep(long millis) throws InterruptedException;
0N/A
0N/A /**
0N/A * Causes the currently executing thread to sleep (temporarily cease
0N/A * execution) for the specified number of milliseconds plus the specified
0N/A * number of nanoseconds, subject to the precision and accuracy of system
0N/A * timers and schedulers. The thread does not lose ownership of any
0N/A * monitors.
0N/A *
0N/A * @param millis
0N/A * the length of time to sleep in milliseconds
0N/A *
0N/A * @param nanos
0N/A * {@code 0-999999} additional nanoseconds to sleep
0N/A *
0N/A * @throws IllegalArgumentException
0N/A * if the value of {@code millis} is negative, or the value of
0N/A * {@code nanos} is not in the range {@code 0-999999}
0N/A *
0N/A * @throws InterruptedException
0N/A * if any thread has interrupted the current thread. The
0N/A * <i>interrupted status</i> of the current thread is
0N/A * cleared when this exception is thrown.
0N/A */
0N/A public static void sleep(long millis, int nanos)
0N/A throws InterruptedException {
0N/A if (millis < 0) {
0N/A throw new IllegalArgumentException("timeout value is negative");
0N/A }
0N/A
0N/A if (nanos < 0 || nanos > 999999) {
0N/A throw new IllegalArgumentException(
0N/A "nanosecond timeout value out of range");
0N/A }
0N/A
0N/A if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
0N/A millis++;
0N/A }
0N/A
0N/A sleep(millis);
0N/A }
0N/A
0N/A /**
0N/A * Initializes a Thread.
0N/A *
0N/A * @param g the Thread group
0N/A * @param target the object whose run() method gets called
0N/A * @param name the name of the new Thread
0N/A * @param stackSize the desired stack size for the new thread, or
0N/A * zero to indicate that this parameter is to be ignored.
0N/A */
0N/A private void init(ThreadGroup g, Runnable target, String name,
0N/A long stackSize) {
520N/A if (name == null) {
520N/A throw new NullPointerException("name cannot be null");
520N/A }
520N/A
0N/A Thread parent = currentThread();
0N/A SecurityManager security = System.getSecurityManager();
0N/A if (g == null) {
0N/A /* Determine if it's an applet or not */
0N/A
0N/A /* If there is a security manager, ask the security manager
0N/A what to do. */
0N/A if (security != null) {
0N/A g = security.getThreadGroup();
0N/A }
0N/A
0N/A /* If the security doesn't have a strong opinion of the matter
0N/A use the parent thread group. */
0N/A if (g == null) {
0N/A g = parent.getThreadGroup();
0N/A }
0N/A }
0N/A
0N/A /* checkAccess regardless of whether or not threadgroup is
0N/A explicitly passed in. */
0N/A g.checkAccess();
0N/A
0N/A /*
0N/A * Do we have the required permissions?
0N/A */
0N/A if (security != null) {
0N/A if (isCCLOverridden(getClass())) {
0N/A security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
0N/A }
0N/A }
0N/A
0N/A g.addUnstarted();
0N/A
0N/A this.group = g;
0N/A this.daemon = parent.isDaemon();
0N/A this.priority = parent.getPriority();
0N/A this.name = name.toCharArray();
0N/A if (security == null || isCCLOverridden(parent.getClass()))
0N/A this.contextClassLoader = parent.getContextClassLoader();
0N/A else
0N/A this.contextClassLoader = parent.contextClassLoader;
0N/A this.inheritedAccessControlContext = AccessController.getContext();
0N/A this.target = target;
0N/A setPriority(priority);
0N/A if (parent.inheritableThreadLocals != null)
0N/A this.inheritableThreadLocals =
0N/A ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
0N/A /* Stash the specified stack size in case the VM cares */
0N/A this.stackSize = stackSize;
0N/A
0N/A /* Set thread ID */
0N/A tid = nextThreadID();
2900N/A }
2900N/A
2900N/A /**
2670N/A * Throws CloneNotSupportedException as a Thread can not be meaningfully
2670N/A * cloned. Construct a new Thread instead.
2900N/A *
2900N/A * @throws CloneNotSupportedException
2670N/A * always
2900N/A */
2900N/A @Override
2900N/A protected Object clone() throws CloneNotSupportedException {
2670N/A throw new CloneNotSupportedException();
0N/A }
0N/A
520N/A /**
520N/A * Allocates a new {@code Thread} object. This constructor has the same
520N/A * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
520N/A * {@code (null, null, gname)}, where {@code gname} is a newly generated
520N/A * name. Automatically generated names are of the form
520N/A * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
0N/A */
0N/A public Thread() {
0N/A init(null, null, "Thread-" + nextThreadNum(), 0);
0N/A }
0N/A
0N/A /**
520N/A * Allocates a new {@code Thread} object. This constructor has the same
520N/A * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
520N/A * {@code (null, target, gname)}, where {@code gname} is a newly generated
520N/A * name. Automatically generated names are of the form
520N/A * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
0N/A *
520N/A * @param target
520N/A * the object whose {@code run} method is invoked when this thread
520N/A * is started. If {@code null}, this classes {@code run} method does
520N/A * nothing.
0N/A */
0N/A public Thread(Runnable target) {
0N/A init(null, target, "Thread-" + nextThreadNum(), 0);
0N/A }
0N/A
0N/A /**
520N/A * Allocates a new {@code Thread} object. This constructor has the same
520N/A * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
520N/A * {@code (group, target, gname)} ,where {@code gname} is a newly generated
520N/A * name. Automatically generated names are of the form
520N/A * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
0N/A *
520N/A * @param group
520N/A * the thread group. If {@code null} and there is a security
520N/A * manager, the group is determined by {@linkplain
520N/A * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
520N/A * If there is not a security manager or {@code
520N/A * SecurityManager.getThreadGroup()} returns {@code null}, the group
520N/A * is set to the current thread's thread group.
520N/A *
520N/A * @param target
520N/A * the object whose {@code run} method is invoked when this thread
520N/A * is started. If {@code null}, this thread's run method is invoked.
520N/A *
520N/A * @throws SecurityException
520N/A * if the current thread cannot create a thread in the specified
520N/A * thread group
0N/A */
0N/A public Thread(ThreadGroup group, Runnable target) {
0N/A init(group, target, "Thread-" + nextThreadNum(), 0);
0N/A }
0N/A
0N/A /**
520N/A * Allocates a new {@code Thread} object. This constructor has the same
520N/A * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
520N/A * {@code (null, null, name)}.
0N/A *
520N/A * @param name
520N/A * the name of the new thread
0N/A */
0N/A public Thread(String name) {
0N/A init(null, null, name, 0);
0N/A }
0N/A
0N/A /**
520N/A * Allocates a new {@code Thread} object. This constructor has the same
520N/A * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
520N/A * {@code (group, null, name)}.
0N/A *
520N/A * @param group
520N/A * the thread group. If {@code null} and there is a security
520N/A * manager, the group is determined by {@linkplain
520N/A * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
520N/A * If there is not a security manager or {@code
520N/A * SecurityManager.getThreadGroup()} returns {@code null}, the group
520N/A * is set to the current thread's thread group.
520N/A *
520N/A * @param name
520N/A * the name of the new thread
520N/A *
520N/A * @throws SecurityException
520N/A * if the current thread cannot create a thread in the specified
520N/A * thread group
0N/A */
0N/A public Thread(ThreadGroup group, String name) {
0N/A init(group, null, name, 0);
0N/A }
0N/A
0N/A /**
520N/A * Allocates a new {@code Thread} object. This constructor has the same
520N/A * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
520N/A * {@code (null, target, name)}.
0N/A *
520N/A * @param target
520N/A * the object whose {@code run} method is invoked when this thread
520N/A * is started. If {@code null}, this thread's run method is invoked.
520N/A *
520N/A * @param name
520N/A * the name of the new thread
0N/A */
0N/A public Thread(Runnable target, String name) {
0N/A init(null, target, name, 0);
0N/A }
0N/A
0N/A /**
520N/A * Allocates a new {@code Thread} object so that it has {@code target}
520N/A * as its run object, has the specified {@code name} as its name,
520N/A * and belongs to the thread group referred to by {@code group}.
0N/A *
520N/A * <p>If there is a security manager, its
520N/A * {@link SecurityManager#checkAccess(ThreadGroup) checkAccess}
520N/A * method is invoked with the ThreadGroup as its argument.
520N/A *
520N/A * <p>In addition, its {@code checkPermission} method is invoked with
520N/A * the {@code RuntimePermission("enableContextClassLoaderOverride")}
0N/A * permission when invoked directly or indirectly by the constructor
520N/A * of a subclass which overrides the {@code getContextClassLoader}
520N/A * or {@code setContextClassLoader} methods.
520N/A *
520N/A * <p>The priority of the newly created thread is set equal to the
0N/A * priority of the thread creating it, that is, the currently running
520N/A * thread. The method {@linkplain #setPriority setPriority} may be
520N/A * used to change the priority to a new value.
520N/A *
520N/A * <p>The newly created thread is initially marked as being a daemon
0N/A * thread if and only if the thread creating it is currently marked
520N/A * as a daemon thread. The method {@linkplain #setDaemon setDaemon}
520N/A * may be used to change whether or not a thread is a daemon.
0N/A *
520N/A * @param group
520N/A * the thread group. If {@code null} and there is a security
520N/A * manager, the group is determined by {@linkplain
520N/A * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
520N/A * If there is not a security manager or {@code
520N/A * SecurityManager.getThreadGroup()} returns {@code null}, the group
520N/A * is set to the current thread's thread group.
520N/A *
520N/A * @param target
520N/A * the object whose {@code run} method is invoked when this thread
520N/A * is started. If {@code null}, this thread's run method is invoked.
520N/A *
520N/A * @param name
520N/A * the name of the new thread
520N/A *
520N/A * @throws SecurityException
520N/A * if the current thread cannot create a thread in the specified
520N/A * thread group or cannot override the context class loader methods.
0N/A */
0N/A public Thread(ThreadGroup group, Runnable target, String name) {
0N/A init(group, target, name, 0);
0N/A }
0N/A
0N/A /**
520N/A * Allocates a new {@code Thread} object so that it has {@code target}
520N/A * as its run object, has the specified {@code name} as its name,
520N/A * and belongs to the thread group referred to by {@code group}, and has
520N/A * the specified <i>stack size</i>.
0N/A *
0N/A * <p>This constructor is identical to {@link
0N/A * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact
0N/A * that it allows the thread stack size to be specified. The stack size
0N/A * is the approximate number of bytes of address space that the virtual
0N/A * machine is to allocate for this thread's stack. <b>The effect of the
520N/A * {@code stackSize} parameter, if any, is highly platform dependent.</b>
0N/A *
0N/A * <p>On some platforms, specifying a higher value for the
520N/A * {@code stackSize} parameter may allow a thread to achieve greater
0N/A * recursion depth before throwing a {@link StackOverflowError}.
0N/A * Similarly, specifying a lower value may allow a greater number of
0N/A * threads to exist concurrently without throwing an {@link
0N/A * OutOfMemoryError} (or other internal error). The details of
0N/A * the relationship between the value of the <tt>stackSize</tt> parameter
0N/A * and the maximum recursion depth and concurrency level are
0N/A * platform-dependent. <b>On some platforms, the value of the
520N/A * {@code stackSize} parameter may have no effect whatsoever.</b>
0N/A *
520N/A * <p>The virtual machine is free to treat the {@code stackSize}
0N/A * parameter as a suggestion. If the specified value is unreasonably low
0N/A * for the platform, the virtual machine may instead use some
0N/A * platform-specific minimum value; if the specified value is unreasonably
0N/A * high, the virtual machine may instead use some platform-specific
0N/A * maximum. Likewise, the virtual machine is free to round the specified
0N/A * value up or down as it sees fit (or to ignore it completely).
0N/A *
520N/A * <p>Specifying a value of zero for the {@code stackSize} parameter will
0N/A * cause this constructor to behave exactly like the
520N/A * {@code Thread(ThreadGroup, Runnable, String)} constructor.
0N/A *
0N/A * <p><i>Due to the platform-dependent nature of the behavior of this
0N/A * constructor, extreme care should be exercised in its use.
0N/A * The thread stack size necessary to perform a given computation will
0N/A * likely vary from one JRE implementation to another. In light of this
0N/A * variation, careful tuning of the stack size parameter may be required,
0N/A * and the tuning may need to be repeated for each JRE implementation on
0N/A * which an application is to run.</i>
0N/A *
0N/A * <p>Implementation note: Java platform implementers are encouraged to
0N/A * document their implementation's behavior with respect to the
520N/A * {@code stackSize} parameter.
520N/A *
520N/A *
520N/A * @param group
520N/A * the thread group. If {@code null} and there is a security
520N/A * manager, the group is determined by {@linkplain
520N/A * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
520N/A * If there is not a security manager or {@code
520N/A * SecurityManager.getThreadGroup()} returns {@code null}, the group
520N/A * is set to the current thread's thread group.
0N/A *
520N/A * @param target
520N/A * the object whose {@code run} method is invoked when this thread
520N/A * is started. If {@code null}, this thread's run method is invoked.
520N/A *
520N/A * @param name
520N/A * the name of the new thread
520N/A *
520N/A * @param stackSize
520N/A * the desired stack size for the new thread, or zero to indicate
520N/A * that this parameter is to be ignored.
520N/A *
520N/A * @throws SecurityException
520N/A * if the current thread cannot create a thread in the specified
520N/A * thread group
520N/A *
0N/A * @since 1.4
0N/A */
0N/A public Thread(ThreadGroup group, Runnable target, String name,
0N/A long stackSize) {
0N/A init(group, target, name, stackSize);
0N/A }
0N/A
0N/A /**
0N/A * Causes this thread to begin execution; the Java Virtual Machine
0N/A * calls the <code>run</code> method of this thread.
0N/A * <p>
0N/A * The result is that two threads are running concurrently: the
0N/A * current thread (which returns from the call to the
0N/A * <code>start</code> method) and the other thread (which executes its
0N/A * <code>run</code> method).
0N/A * <p>
0N/A * It is never legal to start a thread more than once.
0N/A * In particular, a thread may not be restarted once it has completed
0N/A * execution.
0N/A *
0N/A * @exception IllegalThreadStateException if the thread was already
0N/A * started.
0N/A * @see #run()
0N/A * @see #stop()
0N/A */
0N/A public synchronized void start() {
0N/A /**
0N/A * This method is not invoked for the main method thread or "system"
0N/A * group threads created/set up by the VM. Any new functionality added
0N/A * to this method in the future may have to also be added to the VM.
0N/A *
0N/A * A zero status value corresponds to state "NEW".
0N/A */
0N/A if (threadStatus != 0)
0N/A throw new IllegalThreadStateException();
0N/A
0N/A /* Notify the group that this thread is about to be started
3037N/A * so that it can be added to the group's list of threads
3037N/A * and the group's unstarted count can be decremented. */
3505N/A group.add(this);
0N/A
3037N/A boolean started = false;
0N/A try {
0N/A start0();
3037N/A started = true;
0N/A } finally {
0N/A try {
3037N/A if (!started) {
3037N/A group.threadStartFailed(this);
3037N/A }
0N/A } catch (Throwable ignore) {
0N/A /* do nothing. If start0 threw a Throwable then
0N/A it will be passed up the call stack */
0N/A }
0N/A }
0N/A }
0N/A
0N/A private native void start0();
0N/A
0N/A /**
0N/A * If this thread was constructed using a separate
0N/A * <code>Runnable</code> run object, then that
0N/A * <code>Runnable</code> object's <code>run</code> method is called;
0N/A * otherwise, this method does nothing and returns.
0N/A * <p>
0N/A * Subclasses of <code>Thread</code> should override this method.
0N/A *
0N/A * @see #start()
0N/A * @see #stop()
0N/A * @see #Thread(ThreadGroup, Runnable, String)
0N/A */
520N/A @Override
0N/A public void run() {
0N/A if (target != null) {
0N/A target.run();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * This method is called by the system to give a Thread
0N/A * a chance to clean up before it actually exits.
0N/A */
0N/A private void exit() {
0N/A if (group != null) {
0N/A group.threadTerminated(this);
0N/A group = null;
0N/A }
0N/A /* Aggressively null out all reference fields: see bug 4006245 */
0N/A target = null;
0N/A /* Speed the release of some of these resources */
0N/A threadLocals = null;
0N/A inheritableThreadLocals = null;
0N/A inheritedAccessControlContext = null;
0N/A blocker = null;
0N/A uncaughtExceptionHandler = null;
0N/A }
0N/A
0N/A /**
0N/A * Forces the thread to stop executing.
0N/A * <p>
0N/A * If there is a security manager installed, its <code>checkAccess</code>
0N/A * method is called with <code>this</code>
0N/A * as its argument. This may result in a
0N/A * <code>SecurityException</code> being raised (in the current thread).
0N/A * <p>
0N/A * If this thread is different from the current thread (that is, the current
0N/A * thread is trying to stop a thread other than itself), the
0N/A * security manager's <code>checkPermission</code> method (with a
0N/A * <code>RuntimePermission("stopThread")</code> argument) is called in
0N/A * addition.
0N/A * Again, this may result in throwing a
0N/A * <code>SecurityException</code> (in the current thread).
0N/A * <p>
0N/A * The thread represented by this thread is forced to stop whatever
0N/A * it is doing abnormally and to throw a newly created
0N/A * <code>ThreadDeath</code> object as an exception.
0N/A * <p>
0N/A * It is permitted to stop a thread that has not yet been started.
0N/A * If the thread is eventually started, it immediately terminates.
0N/A * <p>
0N/A * An application should not normally try to catch
0N/A * <code>ThreadDeath</code> unless it must do some extraordinary
0N/A * cleanup operation (note that the throwing of
0N/A * <code>ThreadDeath</code> causes <code>finally</code> clauses of
0N/A * <code>try</code> statements to be executed before the thread
0N/A * officially dies). If a <code>catch</code> clause catches a
0N/A * <code>ThreadDeath</code> object, it is important to rethrow the
0N/A * object so that the thread actually dies.
0N/A * <p>
0N/A * The top-level error handler that reacts to otherwise uncaught
0N/A * exceptions does not print out a message or otherwise notify the
0N/A * application if the uncaught exception is an instance of
0N/A * <code>ThreadDeath</code>.
0N/A *
0N/A * @exception SecurityException if the current thread cannot
0N/A * modify this thread.
0N/A * @see #interrupt()
0N/A * @see #checkAccess()
0N/A * @see #run()
0N/A * @see #start()
0N/A * @see ThreadDeath
0N/A * @see ThreadGroup#uncaughtException(Thread,Throwable)
0N/A * @see SecurityManager#checkAccess(Thread)
0N/A * @see SecurityManager#checkPermission
0N/A * @deprecated This method is inherently unsafe. Stopping a thread with
0N/A * Thread.stop causes it to unlock all of the monitors that it
0N/A * has locked (as a natural consequence of the unchecked
0N/A * <code>ThreadDeath</code> exception propagating up the stack). If
0N/A * any of the objects previously protected by these monitors were in
0N/A * an inconsistent state, the damaged objects become visible to
0N/A * other threads, potentially resulting in arbitrary behavior. Many
0N/A * uses of <code>stop</code> should be replaced by code that simply
0N/A * modifies some variable to indicate that the target thread should
0N/A * stop running. The target thread should check this variable
0N/A * regularly, and return from its run method in an orderly fashion
0N/A * if the variable indicates that it is to stop running. If the
0N/A * target thread waits for long periods (on a condition variable,
0N/A * for example), the <code>interrupt</code> method should be used to
0N/A * interrupt the wait.
0N/A * For more information, see
0N/A * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
0N/A * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
0N/A */
0N/A @Deprecated
0N/A public final void stop() {
3581N/A stop(new ThreadDeath());
0N/A }
0N/A
0N/A /**
0N/A * Forces the thread to stop executing.
0N/A * <p>
0N/A * If there is a security manager installed, the <code>checkAccess</code>
0N/A * method of this thread is called, which may result in a
0N/A * <code>SecurityException</code> being raised (in the current thread).
0N/A * <p>
0N/A * If this thread is different from the current thread (that is, the current
0N/A * thread is trying to stop a thread other than itself) or
0N/A * <code>obj</code> is not an instance of <code>ThreadDeath</code>, the
0N/A * security manager's <code>checkPermission</code> method (with the
0N/A * <code>RuntimePermission("stopThread")</code> argument) is called in
0N/A * addition.
0N/A * Again, this may result in throwing a
0N/A * <code>SecurityException</code> (in the current thread).
0N/A * <p>
0N/A * If the argument <code>obj</code> is null, a
0N/A * <code>NullPointerException</code> is thrown (in the current thread).
0N/A * <p>
0N/A * The thread represented by this thread is forced to stop
0N/A * whatever it is doing abnormally and to throw the
0N/A * <code>Throwable</code> object <code>obj</code> as an exception. This
0N/A * is an unusual action to take; normally, the <code>stop</code> method
0N/A * that takes no arguments should be used.
0N/A * <p>
0N/A * It is permitted to stop a thread that has not yet been started.
0N/A * If the thread is eventually started, it immediately terminates.
0N/A *
0N/A * @param obj the Throwable object to be thrown.
0N/A * @exception SecurityException if the current thread cannot modify
0N/A * this thread.
0N/A * @throws NullPointerException if obj is <tt>null</tt>.
0N/A * @see #interrupt()
0N/A * @see #checkAccess()
0N/A * @see #run()
0N/A * @see #start()
0N/A * @see #stop()
0N/A * @see SecurityManager#checkAccess(Thread)
0N/A * @see SecurityManager#checkPermission
0N/A * @deprecated This method is inherently unsafe. See {@link #stop()}
0N/A * for details. An additional danger of this
0N/A * method is that it may be used to generate exceptions that the
0N/A * target thread is unprepared to handle (including checked
0N/A * exceptions that the thread could not possibly throw, were it
0N/A * not for this method).
0N/A * For more information, see
0N/A * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
0N/A * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
0N/A */
0N/A @Deprecated
0N/A public final synchronized void stop(Throwable obj) {
3581N/A if (obj == null)
3581N/A throw new NullPointerException();
0N/A
0N/A SecurityManager security = System.getSecurityManager();
0N/A if (security != null) {
0N/A checkAccess();
0N/A if ((this != Thread.currentThread()) ||
3581N/A (!(obj instanceof ThreadDeath))) {
0N/A security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
0N/A }
0N/A }
3581N/A // A zero status value corresponds to "NEW", it can't change to
3581N/A // not-NEW because we hold the lock.
0N/A if (threadStatus != 0) {
0N/A resume(); // Wake up thread if it was suspended; no-op otherwise
3581N/A }
0N/A
3581N/A // The VM can handle all thread states
3581N/A stop0(obj);
0N/A }
0N/A
0N/A /**
0N/A * Interrupts this thread.
0N/A *
0N/A * <p> Unless the current thread is interrupting itself, which is
0N/A * always permitted, the {@link #checkAccess() checkAccess} method
0N/A * of this thread is invoked, which may cause a {@link
0N/A * SecurityException} to be thrown.
0N/A *
0N/A * <p> If this thread is blocked in an invocation of the {@link
0N/A * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
0N/A * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
0N/A * class, or of the {@link #join()}, {@link #join(long)}, {@link
0N/A * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
0N/A * methods of this class, then its interrupt status will be cleared and it
0N/A * will receive an {@link InterruptedException}.
0N/A *
0N/A * <p> If this thread is blocked in an I/O operation upon an {@link
0N/A * java.nio.channels.InterruptibleChannel </code>interruptible
0N/A * channel<code>} then the channel will be closed, the thread's interrupt
0N/A * status will be set, and the thread will receive a {@link
0N/A * java.nio.channels.ClosedByInterruptException}.
0N/A *
0N/A * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
0N/A * then the thread's interrupt status will be set and it will return
0N/A * immediately from the selection operation, possibly with a non-zero
0N/A * value, just as if the selector's {@link
0N/A * java.nio.channels.Selector#wakeup wakeup} method were invoked.
0N/A *
0N/A * <p> If none of the previous conditions hold then this thread's interrupt
0N/A * status will be set. </p>
0N/A *
0N/A * <p> Interrupting a thread that is not alive need not have any effect.
0N/A *
0N/A * @throws SecurityException
0N/A * if the current thread cannot modify this thread
0N/A *
0N/A * @revised 6.0
0N/A * @spec JSR-51
0N/A */
0N/A public void interrupt() {
0N/A if (this != Thread.currentThread())
0N/A checkAccess();
0N/A
0N/A synchronized (blockerLock) {
0N/A Interruptible b = blocker;
0N/A if (b != null) {
0N/A interrupt0(); // Just to set the interrupt flag
3048N/A b.interrupt(this);
0N/A return;
0N/A }
0N/A }
0N/A interrupt0();
0N/A }
0N/A
0N/A /**
0N/A * Tests whether the current thread has been interrupted. The
0N/A * <i>interrupted status</i> of the thread is cleared by this method. In
0N/A * other words, if this method were to be called twice in succession, the
0N/A * second call would return false (unless the current thread were
0N/A * interrupted again, after the first call had cleared its interrupted
0N/A * status and before the second call had examined it).
0N/A *
0N/A * <p>A thread interruption ignored because a thread was not alive
0N/A * at the time of the interrupt will be reflected by this method
0N/A * returning false.
0N/A *
0N/A * @return <code>true</code> if the current thread has been interrupted;
0N/A * <code>false</code> otherwise.
0N/A * @see #isInterrupted()
0N/A * @revised 6.0
0N/A */
0N/A public static boolean interrupted() {
0N/A return currentThread().isInterrupted(true);
0N/A }
0N/A
0N/A /**
0N/A * Tests whether this thread has been interrupted. The <i>interrupted
0N/A * status</i> of the thread is unaffected by this method.
0N/A *
0N/A * <p>A thread interruption ignored because a thread was not alive
0N/A * at the time of the interrupt will be reflected by this method
0N/A * returning false.
0N/A *
0N/A * @return <code>true</code> if this thread has been interrupted;
0N/A * <code>false</code> otherwise.
0N/A * @see #interrupted()
0N/A * @revised 6.0
0N/A */
0N/A public boolean isInterrupted() {
0N/A return isInterrupted(false);
0N/A }
0N/A
0N/A /**
0N/A * Tests if some Thread has been interrupted. The interrupted state
0N/A * is reset or not based on the value of ClearInterrupted that is
0N/A * passed.
0N/A */
0N/A private native boolean isInterrupted(boolean ClearInterrupted);
0N/A
0N/A /**
0N/A * Throws {@link NoSuchMethodError}.
0N/A *
0N/A * @deprecated This method was originally designed to destroy this
0N/A * thread without any cleanup. Any monitors it held would have
0N/A * remained locked. However, the method was never implemented.
0N/A * If if were to be implemented, it would be deadlock-prone in
0N/A * much the manner of {@link #suspend}. If the target thread held
0N/A * a lock protecting a critical system resource when it was
0N/A * destroyed, no thread could ever access this resource again.
0N/A * If another thread ever attempted to lock this resource, deadlock
0N/A * would result. Such deadlocks typically manifest themselves as
0N/A * "frozen" processes. For more information, see
0N/A * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">
0N/A * Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
0N/A * @throws NoSuchMethodError always
0N/A */
0N/A @Deprecated
0N/A public void destroy() {
0N/A throw new NoSuchMethodError();
0N/A }
0N/A
0N/A /**
0N/A * Tests if this thread is alive. A thread is alive if it has
0N/A * been started and has not yet died.
0N/A *
0N/A * @return <code>true</code> if this thread is alive;
0N/A * <code>false</code> otherwise.
0N/A */
0N/A public final native boolean isAlive();
0N/A
0N/A /**
0N/A * Suspends this thread.
0N/A * <p>
0N/A * First, the <code>checkAccess</code> method of this thread is called
0N/A * with no arguments. This may result in throwing a
0N/A * <code>SecurityException </code>(in the current thread).
0N/A * <p>
0N/A * If the thread is alive, it is suspended and makes no further
0N/A * progress unless and until it is resumed.
0N/A *
0N/A * @exception SecurityException if the current thread cannot modify
0N/A * this thread.
0N/A * @see #checkAccess
0N/A * @deprecated This method has been deprecated, as it is
0N/A * inherently deadlock-prone. If the target thread holds a lock on the
0N/A * monitor protecting a critical system resource when it is suspended, no
0N/A * thread can access this resource until the target thread is resumed. If
0N/A * the thread that would resume the target thread attempts to lock this
0N/A * monitor prior to calling <code>resume</code>, deadlock results. Such
0N/A * deadlocks typically manifest themselves as "frozen" processes.
0N/A * For more information, see
0N/A * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
0N/A * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
0N/A */
0N/A @Deprecated
0N/A public final void suspend() {
0N/A checkAccess();
0N/A suspend0();
0N/A }
0N/A
0N/A /**
0N/A * Resumes a suspended thread.
0N/A * <p>
0N/A * First, the <code>checkAccess</code> method of this thread is called
0N/A * with no arguments. This may result in throwing a
0N/A * <code>SecurityException</code> (in the current thread).
0N/A * <p>
0N/A * If the thread is alive but suspended, it is resumed and is
0N/A * permitted to make progress in its execution.
0N/A *
0N/A * @exception SecurityException if the current thread cannot modify this
0N/A * thread.
0N/A * @see #checkAccess
0N/A * @see #suspend()
0N/A * @deprecated This method exists solely for use with {@link #suspend},
0N/A * which has been deprecated because it is deadlock-prone.
0N/A * For more information, see
0N/A * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
0N/A * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
0N/A */
0N/A @Deprecated
0N/A public final void resume() {
0N/A checkAccess();
0N/A resume0();
0N/A }
0N/A
0N/A /**
0N/A * Changes the priority of this thread.
0N/A * <p>
0N/A * First the <code>checkAccess</code> method of this thread is called
0N/A * with no arguments. This may result in throwing a
0N/A * <code>SecurityException</code>.
0N/A * <p>
0N/A * Otherwise, the priority of this thread is set to the smaller of
0N/A * the specified <code>newPriority</code> and the maximum permitted
0N/A * priority of the thread's thread group.
0N/A *
0N/A * @param newPriority priority to set this thread to
0N/A * @exception IllegalArgumentException If the priority is not in the
0N/A * range <code>MIN_PRIORITY</code> to
0N/A * <code>MAX_PRIORITY</code>.
0N/A * @exception SecurityException if the current thread cannot modify
0N/A * this thread.
0N/A * @see #getPriority
0N/A * @see #checkAccess()
0N/A * @see #getThreadGroup()
0N/A * @see #MAX_PRIORITY
0N/A * @see #MIN_PRIORITY
0N/A * @see ThreadGroup#getMaxPriority()
0N/A */
0N/A public final void setPriority(int newPriority) {
0N/A ThreadGroup g;
0N/A checkAccess();
0N/A if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
0N/A throw new IllegalArgumentException();
0N/A }
0N/A if((g = getThreadGroup()) != null) {
0N/A if (newPriority > g.getMaxPriority()) {
0N/A newPriority = g.getMaxPriority();
0N/A }
0N/A setPriority0(priority = newPriority);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns this thread's priority.
0N/A *
0N/A * @return this thread's priority.
0N/A * @see #setPriority
0N/A */
0N/A public final int getPriority() {
0N/A return priority;
0N/A }
0N/A
0N/A /**
0N/A * Changes the name of this thread to be equal to the argument
0N/A * <code>name</code>.
0N/A * <p>
0N/A * First the <code>checkAccess</code> method of this thread is called
0N/A * with no arguments. This may result in throwing a
0N/A * <code>SecurityException</code>.
0N/A *
0N/A * @param name the new name for this thread.
0N/A * @exception SecurityException if the current thread cannot modify this
0N/A * thread.
0N/A * @see #getName
0N/A * @see #checkAccess()
0N/A */
0N/A public final void setName(String name) {
0N/A checkAccess();
0N/A this.name = name.toCharArray();
0N/A }
0N/A
0N/A /**
0N/A * Returns this thread's name.
0N/A *
0N/A * @return this thread's name.
0N/A * @see #setName(String)
0N/A */
0N/A public final String getName() {
0N/A return String.valueOf(name);
0N/A }
0N/A
0N/A /**
0N/A * Returns the thread group to which this thread belongs.
0N/A * This method returns null if this thread has died
0N/A * (been stopped).
0N/A *
0N/A * @return this thread's thread group.
0N/A */
0N/A public final ThreadGroup getThreadGroup() {
0N/A return group;
0N/A }
0N/A
0N/A /**
0N/A * Returns an estimate of the number of active threads in the current
0N/A * thread's {@linkplain java.lang.ThreadGroup thread group} and its
0N/A * subgroups. Recursively iterates over all subgroups in the current
0N/A * thread's thread group.
0N/A *
0N/A * <p> The value returned is only an estimate because the number of
0N/A * threads may change dynamically while this method traverses internal
0N/A * data structures, and might be affected by the presence of certain
0N/A * system threads. This method is intended primarily for debugging
0N/A * and monitoring purposes.
0N/A *
0N/A * @return an estimate of the number of active threads in the current
0N/A * thread's thread group and in any other thread group that
0N/A * has the current thread's thread group as an ancestor
0N/A */
0N/A public static int activeCount() {
0N/A return currentThread().getThreadGroup().activeCount();
0N/A }
0N/A
0N/A /**
0N/A * Copies into the specified array every active thread in the current
0N/A * thread's thread group and its subgroups. This method simply
0N/A * invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])}
0N/A * method of the current thread's thread group.
0N/A *
0N/A * <p> An application might use the {@linkplain #activeCount activeCount}
0N/A * method to get an estimate of how big the array should be, however
0N/A * <i>if the array is too short to hold all the threads, the extra threads
0N/A * are silently ignored.</i> If it is critical to obtain every active
0N/A * thread in the current thread's thread group and its subgroups, the
0N/A * invoker should verify that the returned int value is strictly less
0N/A * than the length of {@code tarray}.
0N/A *
0N/A * <p> Due to the inherent race condition in this method, it is recommended
0N/A * that the method only be used for debugging and monitoring purposes.
0N/A *
0N/A * @param tarray
0N/A * an array into which to put the list of threads
0N/A *
0N/A * @return the number of threads put into the array
0N/A *
0N/A * @throws SecurityException
0N/A * if {@link java.lang.ThreadGroup#checkAccess} determines that
0N/A * the current thread cannot access its thread group
0N/A */
0N/A public static int enumerate(Thread tarray[]) {
0N/A return currentThread().getThreadGroup().enumerate(tarray);
0N/A }
0N/A
0N/A /**
0N/A * Counts the number of stack frames in this thread. The thread must
0N/A * be suspended.
0N/A *
0N/A * @return the number of stack frames in this thread.
0N/A * @exception IllegalThreadStateException if this thread is not
0N/A * suspended.
0N/A * @deprecated The definition of this call depends on {@link #suspend},
0N/A * which is deprecated. Further, the results of this call
0N/A * were never well-defined.
0N/A */
0N/A @Deprecated
0N/A public native int countStackFrames();
0N/A
0N/A /**
0N/A * Waits at most {@code millis} milliseconds for this thread to
0N/A * die. A timeout of {@code 0} means to wait forever.
0N/A *
0N/A * <p> This implementation uses a loop of {@code this.wait} calls
0N/A * conditioned on {@code this.isAlive}. As a thread terminates the
0N/A * {@code this.notifyAll} method is invoked. It is recommended that
0N/A * applications not use {@code wait}, {@code notify}, or
0N/A * {@code notifyAll} on {@code Thread} instances.
0N/A *
0N/A * @param millis
0N/A * the time to wait in milliseconds
0N/A *
0N/A * @throws IllegalArgumentException
0N/A * if the value of {@code millis} is negative
0N/A *
0N/A * @throws InterruptedException
0N/A * if any thread has interrupted the current thread. The
0N/A * <i>interrupted status</i> of the current thread is
0N/A * cleared when this exception is thrown.
0N/A */
0N/A public final synchronized void join(long millis)
0N/A throws InterruptedException {
0N/A long base = System.currentTimeMillis();
0N/A long now = 0;
0N/A
0N/A if (millis < 0) {
0N/A throw new IllegalArgumentException("timeout value is negative");
0N/A }
0N/A
0N/A if (millis == 0) {
0N/A while (isAlive()) {
0N/A wait(0);
0N/A }
0N/A } else {
0N/A while (isAlive()) {
0N/A long delay = millis - now;
0N/A if (delay <= 0) {
0N/A break;
0N/A }
0N/A wait(delay);
0N/A now = System.currentTimeMillis() - base;
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Waits at most {@code millis} milliseconds plus
0N/A * {@code nanos} nanoseconds for this thread to die.
0N/A *
0N/A * <p> This implementation uses a loop of {@code this.wait} calls
0N/A * conditioned on {@code this.isAlive}. As a thread terminates the
0N/A * {@code this.notifyAll} method is invoked. It is recommended that
0N/A * applications not use {@code wait}, {@code notify}, or
0N/A * {@code notifyAll} on {@code Thread} instances.
0N/A *
0N/A * @param millis
0N/A * the time to wait in milliseconds
0N/A *
0N/A * @param nanos
0N/A * {@code 0-999999} additional nanoseconds to wait
0N/A *
0N/A * @throws IllegalArgumentException
0N/A * if the value of {@code millis} is negative, or the value
0N/A * of {@code nanos} is not in the range {@code 0-999999}
0N/A *
0N/A * @throws InterruptedException
0N/A * if any thread has interrupted the current thread. The
0N/A * <i>interrupted status</i> of the current thread is
0N/A * cleared when this exception is thrown.
0N/A */
0N/A public final synchronized void join(long millis, int nanos)
0N/A throws InterruptedException {
0N/A
0N/A if (millis < 0) {
0N/A throw new IllegalArgumentException("timeout value is negative");
0N/A }
0N/A
0N/A if (nanos < 0 || nanos > 999999) {
0N/A throw new IllegalArgumentException(
0N/A "nanosecond timeout value out of range");
0N/A }
0N/A
0N/A if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
0N/A millis++;
0N/A }
0N/A
0N/A join(millis);
0N/A }
0N/A
0N/A /**
0N/A * Waits for this thread to die.
0N/A *
0N/A * <p> An invocation of this method behaves in exactly the same
0N/A * way as the invocation
0N/A *
0N/A * <blockquote>
0N/A * {@linkplain #join(long) join}{@code (0)}
0N/A * </blockquote>
0N/A *
0N/A * @throws InterruptedException
0N/A * if any thread has interrupted the current thread. The
0N/A * <i>interrupted status</i> of the current thread is
0N/A * cleared when this exception is thrown.
0N/A */
0N/A public final void join() throws InterruptedException {
0N/A join(0);
0N/A }
0N/A
0N/A /**
0N/A * Prints a stack trace of the current thread to the standard error stream.
0N/A * This method is used only for debugging.
0N/A *
0N/A * @see Throwable#printStackTrace()
0N/A */
0N/A public static void dumpStack() {
0N/A new Exception("Stack trace").printStackTrace();
0N/A }
0N/A
0N/A /**
0N/A * Marks this thread as either a {@linkplain #isDaemon daemon} thread
0N/A * or a user thread. The Java Virtual Machine exits when the only
0N/A * threads running are all daemon threads.
0N/A *
0N/A * <p> This method must be invoked before the thread is started.
0N/A *
0N/A * @param on
0N/A * if {@code true}, marks this thread as a daemon thread
0N/A *
0N/A * @throws IllegalThreadStateException
0N/A * if this thread is {@linkplain #isAlive alive}
0N/A *
0N/A * @throws SecurityException
0N/A * if {@link #checkAccess} determines that the current
0N/A * thread cannot modify this thread
0N/A */
0N/A public final void setDaemon(boolean on) {
0N/A checkAccess();
0N/A if (isAlive()) {
0N/A throw new IllegalThreadStateException();
0N/A }
0N/A daemon = on;
0N/A }
0N/A
0N/A /**
0N/A * Tests if this thread is a daemon thread.
0N/A *
0N/A * @return <code>true</code> if this thread is a daemon thread;
0N/A * <code>false</code> otherwise.
0N/A * @see #setDaemon(boolean)
0N/A */
0N/A public final boolean isDaemon() {
0N/A return daemon;
0N/A }
0N/A
0N/A /**
0N/A * Determines if the currently running thread has permission to
0N/A * modify this thread.
0N/A * <p>
0N/A * If there is a security manager, its <code>checkAccess</code> method
0N/A * is called with this thread as its argument. This may result in
0N/A * throwing a <code>SecurityException</code>.
0N/A *
0N/A * @exception SecurityException if the current thread is not allowed to
0N/A * access this thread.
0N/A * @see SecurityManager#checkAccess(Thread)
0N/A */
0N/A public final void checkAccess() {
0N/A SecurityManager security = System.getSecurityManager();
0N/A if (security != null) {
0N/A security.checkAccess(this);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a string representation of this thread, including the
0N/A * thread's name, priority, and thread group.
0N/A *
0N/A * @return a string representation of this thread.
0N/A */
0N/A public String toString() {
0N/A ThreadGroup group = getThreadGroup();
0N/A if (group != null) {
0N/A return "Thread[" + getName() + "," + getPriority() + "," +
0N/A group.getName() + "]";
0N/A } else {
0N/A return "Thread[" + getName() + "," + getPriority() + "," +
0N/A "" + "]";
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns the context ClassLoader for this Thread. The context
0N/A * ClassLoader is provided by the creator of the thread for use
0N/A * by code running in this thread when loading classes and resources.
520N/A * If not {@linkplain #setContextClassLoader set}, the default is the
520N/A * ClassLoader context of the parent Thread. The context ClassLoader of the
520N/A * primordial thread is typically set to the class loader used to load the
520N/A * application.
0N/A *
520N/A * <p>If a security manager is present, and the invoker's class loader is not
520N/A * {@code null} and is not the same as or an ancestor of the context class
520N/A * loader, then this method invokes the security manager's {@link
520N/A * SecurityManager#checkPermission(java.security.Permission) checkPermission}
520N/A * method with a {@link RuntimePermission RuntimePermission}{@code
520N/A * ("getClassLoader")} permission to verify that retrieval of the context
520N/A * class loader is permitted.
0N/A *
520N/A * @return the context ClassLoader for this Thread, or {@code null}
520N/A * indicating the system class loader (or, failing that, the
520N/A * bootstrap class loader)
0N/A *
520N/A * @throws SecurityException
520N/A * if the current thread cannot get the context ClassLoader
0N/A *
0N/A * @since 1.2
0N/A */
6338N/A @CallerSensitive
0N/A public ClassLoader getContextClassLoader() {
0N/A if (contextClassLoader == null)
0N/A return null;
6338N/A
0N/A SecurityManager sm = System.getSecurityManager();
0N/A if (sm != null) {
6338N/A ClassLoader.checkClassLoaderPermission(contextClassLoader,
6338N/A Reflection.getCallerClass());
0N/A }
0N/A return contextClassLoader;
0N/A }
0N/A
0N/A /**
0N/A * Sets the context ClassLoader for this Thread. The context
0N/A * ClassLoader can be set when a thread is created, and allows
520N/A * the creator of the thread to provide the appropriate class loader,
520N/A * through {@code getContextClassLoader}, to code running in the thread
520N/A * when loading classes and resources.
0N/A *
520N/A * <p>If a security manager is present, its {@link
520N/A * SecurityManager#checkPermission(java.security.Permission) checkPermission}
520N/A * method is invoked with a {@link RuntimePermission RuntimePermission}{@code
520N/A * ("setContextClassLoader")} permission to see if setting the context
520N/A * ClassLoader is permitted.
0N/A *
520N/A * @param cl
520N/A * the context ClassLoader for this Thread, or null indicating the
520N/A * system class loader (or, failing that, the bootstrap class loader)
520N/A *
520N/A * @throws SecurityException
520N/A * if the current thread cannot set the context ClassLoader
0N/A *
0N/A * @since 1.2
0N/A */
0N/A public void setContextClassLoader(ClassLoader cl) {
0N/A SecurityManager sm = System.getSecurityManager();
0N/A if (sm != null) {
0N/A sm.checkPermission(new RuntimePermission("setContextClassLoader"));
0N/A }
0N/A contextClassLoader = cl;
0N/A }
0N/A
0N/A /**
0N/A * Returns <tt>true</tt> if and only if the current thread holds the
0N/A * monitor lock on the specified object.
0N/A *
0N/A * <p>This method is designed to allow a program to assert that
0N/A * the current thread already holds a specified lock:
0N/A * <pre>
0N/A * assert Thread.holdsLock(obj);
0N/A * </pre>
0N/A *
0N/A * @param obj the object on which to test lock ownership
0N/A * @throws NullPointerException if obj is <tt>null</tt>
0N/A * @return <tt>true</tt> if the current thread holds the monitor lock on
0N/A * the specified object.
0N/A * @since 1.4
0N/A */
0N/A public static native boolean holdsLock(Object obj);
0N/A
0N/A private static final StackTraceElement[] EMPTY_STACK_TRACE
0N/A = new StackTraceElement[0];
0N/A
0N/A /**
0N/A * Returns an array of stack trace elements representing the stack dump
0N/A * of this thread. This method will return a zero-length array if
0N/A * this thread has not started, has started but has not yet been
0N/A * scheduled to run by the system, or has terminated.
0N/A * If the returned array is of non-zero length then the first element of
0N/A * the array represents the top of the stack, which is the most recent
0N/A * method invocation in the sequence. The last element of the array
0N/A * represents the bottom of the stack, which is the least recent method
0N/A * invocation in the sequence.
0N/A *
0N/A * <p>If there is a security manager, and this thread is not
0N/A * the current thread, then the security manager's
0N/A * <tt>checkPermission</tt> method is called with a
0N/A * <tt>RuntimePermission("getStackTrace")</tt> permission
0N/A * to see if it's ok to get the stack trace.
0N/A *
0N/A * <p>Some virtual machines may, under some circumstances, omit one
0N/A * or more stack frames from the stack trace. In the extreme case,
0N/A * a virtual machine that has no stack trace information concerning
0N/A * this thread is permitted to return a zero-length array from this
0N/A * method.
0N/A *
0N/A * @return an array of <tt>StackTraceElement</tt>,
0N/A * each represents one stack frame.
0N/A *
0N/A * @throws SecurityException
0N/A * if a security manager exists and its
0N/A * <tt>checkPermission</tt> method doesn't allow
0N/A * getting the stack trace of thread.
0N/A * @see SecurityManager#checkPermission
0N/A * @see RuntimePermission
0N/A * @see Throwable#getStackTrace
0N/A *
0N/A * @since 1.5
0N/A */
0N/A public StackTraceElement[] getStackTrace() {
0N/A if (this != Thread.currentThread()) {
0N/A // check for getStackTrace permission
0N/A SecurityManager security = System.getSecurityManager();
0N/A if (security != null) {
0N/A security.checkPermission(
0N/A SecurityConstants.GET_STACK_TRACE_PERMISSION);
0N/A }
0N/A // optimization so we do not call into the vm for threads that
0N/A // have not yet started or have terminated
0N/A if (!isAlive()) {
0N/A return EMPTY_STACK_TRACE;
0N/A }
0N/A StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
0N/A StackTraceElement[] stackTrace = stackTraceArray[0];
0N/A // a thread that was alive during the previous isAlive call may have
0N/A // since terminated, therefore not having a stacktrace.
0N/A if (stackTrace == null) {
0N/A stackTrace = EMPTY_STACK_TRACE;
0N/A }
0N/A return stackTrace;
0N/A } else {
0N/A // Don't need JVM help for current thread
0N/A return (new Exception()).getStackTrace();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a map of stack traces for all live threads.
0N/A * The map keys are threads and each map value is an array of
0N/A * <tt>StackTraceElement</tt> that represents the stack dump
0N/A * of the corresponding <tt>Thread</tt>.
0N/A * The returned stack traces are in the format specified for
0N/A * the {@link #getStackTrace getStackTrace} method.
0N/A *
0N/A * <p>The threads may be executing while this method is called.
0N/A * The stack trace of each thread only represents a snapshot and
0N/A * each stack trace may be obtained at different time. A zero-length
0N/A * array will be returned in the map value if the virtual machine has
0N/A * no stack trace information about a thread.
0N/A *
0N/A * <p>If there is a security manager, then the security manager's
0N/A * <tt>checkPermission</tt> method is called with a
0N/A * <tt>RuntimePermission("getStackTrace")</tt> permission as well as
0N/A * <tt>RuntimePermission("modifyThreadGroup")</tt> permission
0N/A * to see if it is ok to get the stack trace of all threads.
0N/A *
0N/A * @return a <tt>Map</tt> from <tt>Thread</tt> to an array of
0N/A * <tt>StackTraceElement</tt> that represents the stack trace of
0N/A * the corresponding thread.
0N/A *
0N/A * @throws SecurityException
0N/A * if a security manager exists and its
0N/A * <tt>checkPermission</tt> method doesn't allow
0N/A * getting the stack trace of thread.
0N/A * @see #getStackTrace
0N/A * @see SecurityManager#checkPermission
0N/A * @see RuntimePermission
0N/A * @see Throwable#getStackTrace
0N/A *
0N/A * @since 1.5
0N/A */
0N/A public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
0N/A // check for getStackTrace permission
0N/A SecurityManager security = System.getSecurityManager();
0N/A if (security != null) {
0N/A security.checkPermission(
0N/A SecurityConstants.GET_STACK_TRACE_PERMISSION);
0N/A security.checkPermission(
0N/A SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
0N/A }
0N/A
0N/A // Get a snapshot of the list of all threads
0N/A Thread[] threads = getThreads();
0N/A StackTraceElement[][] traces = dumpThreads(threads);
3323N/A Map<Thread, StackTraceElement[]> m = new HashMap<>(threads.length);
0N/A for (int i = 0; i < threads.length; i++) {
0N/A StackTraceElement[] stackTrace = traces[i];
0N/A if (stackTrace != null) {
0N/A m.put(threads[i], stackTrace);
0N/A }
0N/A // else terminated so we don't put it in the map
0N/A }
0N/A return m;
0N/A }
0N/A
0N/A
0N/A private static final RuntimePermission SUBCLASS_IMPLEMENTATION_PERMISSION =
0N/A new RuntimePermission("enableContextClassLoaderOverride");
0N/A
0N/A /** cache of subclass security audit results */
905N/A /* Replace with ConcurrentReferenceHashMap when/if it appears in a future
905N/A * release */
905N/A private static class Caches {
905N/A /** cache of subclass security audit results */
905N/A static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
3323N/A new ConcurrentHashMap<>();
0N/A
905N/A /** queue for WeakReferences to audited subclasses */
905N/A static final ReferenceQueue<Class<?>> subclassAuditsQueue =
3323N/A new ReferenceQueue<>();
905N/A }
0N/A
0N/A /**
0N/A * Verifies that this (possibly subclass) instance can be constructed
0N/A * without violating security constraints: the subclass must not override
0N/A * security-sensitive non-final methods, or else the
0N/A * "enableContextClassLoaderOverride" RuntimePermission is checked.
0N/A */
0N/A private static boolean isCCLOverridden(Class cl) {
0N/A if (cl == Thread.class)
0N/A return false;
905N/A
905N/A processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
905N/A WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
905N/A Boolean result = Caches.subclassAudits.get(key);
905N/A if (result == null) {
905N/A result = Boolean.valueOf(auditSubclass(cl));
905N/A Caches.subclassAudits.putIfAbsent(key, result);
0N/A }
905N/A
0N/A return result.booleanValue();
0N/A }
0N/A
0N/A /**
0N/A * Performs reflective checks on given subclass to verify that it doesn't
0N/A * override security-sensitive non-final methods. Returns true if the
0N/A * subclass overrides any of the methods, false otherwise.
0N/A */
0N/A private static boolean auditSubclass(final Class subcl) {
0N/A Boolean result = AccessController.doPrivileged(
0N/A new PrivilegedAction<Boolean>() {
0N/A public Boolean run() {
0N/A for (Class cl = subcl;
0N/A cl != Thread.class;
0N/A cl = cl.getSuperclass())
0N/A {
0N/A try {
0N/A cl.getDeclaredMethod("getContextClassLoader", new Class[0]);
0N/A return Boolean.TRUE;
0N/A } catch (NoSuchMethodException ex) {
0N/A }
0N/A try {
0N/A Class[] params = {ClassLoader.class};
0N/A cl.getDeclaredMethod("setContextClassLoader", params);
0N/A return Boolean.TRUE;
0N/A } catch (NoSuchMethodException ex) {
0N/A }
0N/A }
0N/A return Boolean.FALSE;
0N/A }
0N/A }
0N/A );
0N/A return result.booleanValue();
0N/A }
0N/A
0N/A private native static StackTraceElement[][] dumpThreads(Thread[] threads);
0N/A private native static Thread[] getThreads();
0N/A
0N/A /**
0N/A * Returns the identifier of this Thread. The thread ID is a positive
0N/A * <tt>long</tt> number generated when this thread was created.
0N/A * The thread ID is unique and remains unchanged during its lifetime.
0N/A * When a thread is terminated, this thread ID may be reused.
0N/A *
0N/A * @return this thread's ID.
0N/A * @since 1.5
0N/A */
0N/A public long getId() {
0N/A return tid;
0N/A }
0N/A
0N/A /**
0N/A * A thread state. A thread can be in one of the following states:
0N/A * <ul>
0N/A * <li>{@link #NEW}<br>
0N/A * A thread that has not yet started is in this state.
0N/A * </li>
0N/A * <li>{@link #RUNNABLE}<br>
0N/A * A thread executing in the Java virtual machine is in this state.
0N/A * </li>
0N/A * <li>{@link #BLOCKED}<br>
0N/A * A thread that is blocked waiting for a monitor lock
0N/A * is in this state.
0N/A * </li>
0N/A * <li>{@link #WAITING}<br>
0N/A * A thread that is waiting indefinitely for another thread to
0N/A * perform a particular action is in this state.
0N/A * </li>
0N/A * <li>{@link #TIMED_WAITING}<br>
0N/A * A thread that is waiting for another thread to perform an action
0N/A * for up to a specified waiting time is in this state.
0N/A * </li>
0N/A * <li>{@link #TERMINATED}<br>
0N/A * A thread that has exited is in this state.
0N/A * </li>
0N/A * </ul>
0N/A *
0N/A * <p>
0N/A * A thread can be in only one state at a given point in time.
0N/A * These states are virtual machine states which do not reflect
0N/A * any operating system thread states.
0N/A *
0N/A * @since 1.5
0N/A * @see #getState
0N/A */
0N/A public enum State {
0N/A /**
0N/A * Thread state for a thread which has not yet started.
0N/A */
0N/A NEW,
0N/A
0N/A /**
0N/A * Thread state for a runnable thread. A thread in the runnable
0N/A * state is executing in the Java virtual machine but it may
0N/A * be waiting for other resources from the operating system
0N/A * such as processor.
0N/A */
0N/A RUNNABLE,
0N/A
0N/A /**
0N/A * Thread state for a thread blocked waiting for a monitor lock.
0N/A * A thread in the blocked state is waiting for a monitor lock
0N/A * to enter a synchronized block/method or
0N/A * reenter a synchronized block/method after calling
0N/A * {@link Object#wait() Object.wait}.
0N/A */
0N/A BLOCKED,
0N/A
0N/A /**
0N/A * Thread state for a waiting thread.
0N/A * A thread is in the waiting state due to calling one of the
0N/A * following methods:
0N/A * <ul>
0N/A * <li>{@link Object#wait() Object.wait} with no timeout</li>
0N/A * <li>{@link #join() Thread.join} with no timeout</li>
0N/A * <li>{@link LockSupport#park() LockSupport.park}</li>
0N/A * </ul>
0N/A *
0N/A * <p>A thread in the waiting state is waiting for another thread to
0N/A * perform a particular action.
0N/A *
0N/A * For example, a thread that has called <tt>Object.wait()</tt>
0N/A * on an object is waiting for another thread to call
0N/A * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
0N/A * that object. A thread that has called <tt>Thread.join()</tt>
0N/A * is waiting for a specified thread to terminate.
0N/A */
0N/A WAITING,
0N/A
0N/A /**
0N/A * Thread state for a waiting thread with a specified waiting time.
0N/A * A thread is in the timed waiting state due to calling one of
0N/A * the following methods with a specified positive waiting time:
0N/A * <ul>
0N/A * <li>{@link #sleep Thread.sleep}</li>
0N/A * <li>{@link Object#wait(long) Object.wait} with timeout</li>
0N/A * <li>{@link #join(long) Thread.join} with timeout</li>
0N/A * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
0N/A * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
0N/A * </ul>
0N/A */
0N/A TIMED_WAITING,
0N/A
0N/A /**
0N/A * Thread state for a terminated thread.
0N/A * The thread has completed execution.
0N/A */
0N/A TERMINATED;
0N/A }
0N/A
0N/A /**
0N/A * Returns the state of this thread.
0N/A * This method is designed for use in monitoring of the system state,
0N/A * not for synchronization control.
0N/A *
0N/A * @return this thread's state.
0N/A * @since 1.5
0N/A */
0N/A public State getState() {
0N/A // get current thread state
0N/A return sun.misc.VM.toThreadState(threadStatus);
0N/A }
0N/A
0N/A // Added in JSR-166
0N/A
0N/A /**
0N/A * Interface for handlers invoked when a <tt>Thread</tt> abruptly
0N/A * terminates due to an uncaught exception.
0N/A * <p>When a thread is about to terminate due to an uncaught exception
0N/A * the Java Virtual Machine will query the thread for its
0N/A * <tt>UncaughtExceptionHandler</tt> using
0N/A * {@link #getUncaughtExceptionHandler} and will invoke the handler's
0N/A * <tt>uncaughtException</tt> method, passing the thread and the
0N/A * exception as arguments.
0N/A * If a thread has not had its <tt>UncaughtExceptionHandler</tt>
0N/A * explicitly set, then its <tt>ThreadGroup</tt> object acts as its
0N/A * <tt>UncaughtExceptionHandler</tt>. If the <tt>ThreadGroup</tt> object
0N/A * has no
0N/A * special requirements for dealing with the exception, it can forward
0N/A * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
0N/A * default uncaught exception handler}.
0N/A *
0N/A * @see #setDefaultUncaughtExceptionHandler
0N/A * @see #setUncaughtExceptionHandler
0N/A * @see ThreadGroup#uncaughtException
0N/A * @since 1.5
0N/A */
0N/A public interface UncaughtExceptionHandler {
0N/A /**
0N/A * Method invoked when the given thread terminates due to the
0N/A * given uncaught exception.
0N/A * <p>Any exception thrown by this method will be ignored by the
0N/A * Java Virtual Machine.
0N/A * @param t the thread
0N/A * @param e the exception
0N/A */
0N/A void uncaughtException(Thread t, Throwable e);
0N/A }
0N/A
0N/A // null unless explicitly set
0N/A private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
0N/A
0N/A // null unless explicitly set
0N/A private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
0N/A
0N/A /**
0N/A * Set the default handler invoked when a thread abruptly terminates
0N/A * due to an uncaught exception, and no other handler has been defined
0N/A * for that thread.
0N/A *
0N/A * <p>Uncaught exception handling is controlled first by the thread, then
0N/A * by the thread's {@link ThreadGroup} object and finally by the default
0N/A * uncaught exception handler. If the thread does not have an explicit
0N/A * uncaught exception handler set, and the thread's thread group
0N/A * (including parent thread groups) does not specialize its
0N/A * <tt>uncaughtException</tt> method, then the default handler's
0N/A * <tt>uncaughtException</tt> method will be invoked.
0N/A * <p>By setting the default uncaught exception handler, an application
0N/A * can change the way in which uncaught exceptions are handled (such as
0N/A * logging to a specific device, or file) for those threads that would
0N/A * already accept whatever &quot;default&quot; behavior the system
0N/A * provided.
0N/A *
0N/A * <p>Note that the default uncaught exception handler should not usually
0N/A * defer to the thread's <tt>ThreadGroup</tt> object, as that could cause
0N/A * infinite recursion.
0N/A *
0N/A * @param eh the object to use as the default uncaught exception handler.
0N/A * If <tt>null</tt> then there is no default handler.
0N/A *
0N/A * @throws SecurityException if a security manager is present and it
0N/A * denies <tt>{@link RuntimePermission}
0N/A * (&quot;setDefaultUncaughtExceptionHandler&quot;)</tt>
0N/A *
0N/A * @see #setUncaughtExceptionHandler
0N/A * @see #getUncaughtExceptionHandler
0N/A * @see ThreadGroup#uncaughtException
0N/A * @since 1.5
0N/A */
0N/A public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
0N/A SecurityManager sm = System.getSecurityManager();
0N/A if (sm != null) {
0N/A sm.checkPermission(
0N/A new RuntimePermission("setDefaultUncaughtExceptionHandler")
0N/A );
0N/A }
0N/A
0N/A defaultUncaughtExceptionHandler = eh;
0N/A }
0N/A
0N/A /**
0N/A * Returns the default handler invoked when a thread abruptly terminates
0N/A * due to an uncaught exception. If the returned value is <tt>null</tt>,
0N/A * there is no default.
0N/A * @since 1.5
0N/A * @see #setDefaultUncaughtExceptionHandler
0N/A */
0N/A public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
0N/A return defaultUncaughtExceptionHandler;
0N/A }
0N/A
0N/A /**
0N/A * Returns the handler invoked when this thread abruptly terminates
0N/A * due to an uncaught exception. If this thread has not had an
0N/A * uncaught exception handler explicitly set then this thread's
0N/A * <tt>ThreadGroup</tt> object is returned, unless this thread
0N/A * has terminated, in which case <tt>null</tt> is returned.
0N/A * @since 1.5
0N/A */
0N/A public UncaughtExceptionHandler getUncaughtExceptionHandler() {
0N/A return uncaughtExceptionHandler != null ?
0N/A uncaughtExceptionHandler : group;
0N/A }
0N/A
0N/A /**
0N/A * Set the handler invoked when this thread abruptly terminates
0N/A * due to an uncaught exception.
0N/A * <p>A thread can take full control of how it responds to uncaught
0N/A * exceptions by having its uncaught exception handler explicitly set.
0N/A * If no such handler is set then the thread's <tt>ThreadGroup</tt>
0N/A * object acts as its handler.
0N/A * @param eh the object to use as this thread's uncaught exception
0N/A * handler. If <tt>null</tt> then this thread has no explicit handler.
0N/A * @throws SecurityException if the current thread is not allowed to
0N/A * modify this thread.
0N/A * @see #setDefaultUncaughtExceptionHandler
0N/A * @see ThreadGroup#uncaughtException
0N/A * @since 1.5
0N/A */
0N/A public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
0N/A checkAccess();
0N/A uncaughtExceptionHandler = eh;
0N/A }
0N/A
0N/A /**
0N/A * Dispatch an uncaught exception to the handler. This method is
0N/A * intended to be called only by the JVM.
0N/A */
0N/A private void dispatchUncaughtException(Throwable e) {
0N/A getUncaughtExceptionHandler().uncaughtException(this, e);
0N/A }
0N/A
905N/A /**
905N/A * Removes from the specified map any keys that have been enqueued
905N/A * on the specified reference queue.
905N/A */
905N/A static void processQueue(ReferenceQueue<Class<?>> queue,
905N/A ConcurrentMap<? extends
905N/A WeakReference<Class<?>>, ?> map)
905N/A {
905N/A Reference<? extends Class<?>> ref;
905N/A while((ref = queue.poll()) != null) {
905N/A map.remove(ref);
905N/A }
905N/A }
905N/A
905N/A /**
905N/A * Weak key for Class objects.
905N/A **/
905N/A static class WeakClassKey extends WeakReference<Class<?>> {
905N/A /**
905N/A * saved value of the referent's identity hash code, to maintain
905N/A * a consistent hash code after the referent has been cleared
905N/A */
905N/A private final int hash;
905N/A
905N/A /**
905N/A * Create a new WeakClassKey to the given object, registered
905N/A * with a queue.
905N/A */
905N/A WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) {
905N/A super(cl, refQueue);
905N/A hash = System.identityHashCode(cl);
905N/A }
905N/A
905N/A /**
905N/A * Returns the identity hash code of the original referent.
905N/A */
905N/A @Override
905N/A public int hashCode() {
905N/A return hash;
905N/A }
905N/A
905N/A /**
905N/A * Returns true if the given object is this identical
905N/A * WeakClassKey instance, or, if this object's referent has not
905N/A * been cleared, if the given object is another WeakClassKey
905N/A * instance with the identical non-null referent as this one.
905N/A */
905N/A @Override
905N/A public boolean equals(Object obj) {
905N/A if (obj == this)
905N/A return true;
905N/A
905N/A if (obj instanceof WeakClassKey) {
905N/A Object referent = get();
905N/A return (referent != null) &&
905N/A (referent == ((WeakClassKey) obj).get());
905N/A } else {
905N/A return false;
905N/A }
905N/A }
905N/A }
905N/A
0N/A /* Some private helper methods */
0N/A private native void setPriority0(int newPriority);
0N/A private native void stop0(Object o);
0N/A private native void suspend0();
0N/A private native void resume0();
0N/A private native void interrupt0();
4632N/A private native void setNativeName(String name);
0N/A}