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