0001: /*
0002: * Copyright 1994-2007 Sun Microsystems, Inc. All Rights Reserved.
0003: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0004: *
0005: * This code is free software; you can redistribute it and/or modify it
0006: * under the terms of the GNU General Public License version 2 only, as
0007: * published by the Free Software Foundation. Sun designates this
0008: * particular file as subject to the "Classpath" exception as provided
0009: * by Sun in the LICENSE file that accompanied this code.
0010: *
0011: * This code is distributed in the hope that it will be useful, but WITHOUT
0012: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0013: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0014: * version 2 for more details (a copy is included in the LICENSE file that
0015: * accompanied this code).
0016: *
0017: * You should have received a copy of the GNU General Public License version
0018: * 2 along with this work; if not, write to the Free Software Foundation,
0019: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0020: *
0021: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
0022: * CA 95054 USA or visit www.sun.com if you need additional information or
0023: * have any questions.
0024: */
0025:
0026: package java.lang;
0027:
0028: import java.security.AccessController;
0029: import java.security.AccessControlContext;
0030: import java.security.PrivilegedAction;
0031: import java.util.Map;
0032: import java.util.HashMap;
0033: import java.util.Collections;
0034: import java.util.concurrent.locks.LockSupport;
0035: import sun.misc.SoftCache;
0036: import sun.nio.ch.Interruptible;
0037: import sun.security.util.SecurityConstants;
0038:
0039: /**
0040: * A <i>thread</i> is a thread of execution in a program. The Java
0041: * Virtual Machine allows an application to have multiple threads of
0042: * execution running concurrently.
0043: * <p>
0044: * Every thread has a priority. Threads with higher priority are
0045: * executed in preference to threads with lower priority. Each thread
0046: * may or may not also be marked as a daemon. When code running in
0047: * some thread creates a new <code>Thread</code> object, the new
0048: * thread has its priority initially set equal to the priority of the
0049: * creating thread, and is a daemon thread if and only if the
0050: * creating thread is a daemon.
0051: * <p>
0052: * When a Java Virtual Machine starts up, there is usually a single
0053: * non-daemon thread (which typically calls the method named
0054: * <code>main</code> of some designated class). The Java Virtual
0055: * Machine continues to execute threads until either of the following
0056: * occurs:
0057: * <ul>
0058: * <li>The <code>exit</code> method of class <code>Runtime</code> has been
0059: * called and the security manager has permitted the exit operation
0060: * to take place.
0061: * <li>All threads that are not daemon threads have died, either by
0062: * returning from the call to the <code>run</code> method or by
0063: * throwing an exception that propagates beyond the <code>run</code>
0064: * method.
0065: * </ul>
0066: * <p>
0067: * There are two ways to create a new thread of execution. One is to
0068: * declare a class to be a subclass of <code>Thread</code>. This
0069: * subclass should override the <code>run</code> method of class
0070: * <code>Thread</code>. An instance of the subclass can then be
0071: * allocated and started. For example, a thread that computes primes
0072: * larger than a stated value could be written as follows:
0073: * <p><hr><blockquote><pre>
0074: * class PrimeThread extends Thread {
0075: * long minPrime;
0076: * PrimeThread(long minPrime) {
0077: * this.minPrime = minPrime;
0078: * }
0079: *
0080: * public void run() {
0081: * // compute primes larger than minPrime
0082: * . . .
0083: * }
0084: * }
0085: * </pre></blockquote><hr>
0086: * <p>
0087: * The following code would then create a thread and start it running:
0088: * <p><blockquote><pre>
0089: * PrimeThread p = new PrimeThread(143);
0090: * p.start();
0091: * </pre></blockquote>
0092: * <p>
0093: * The other way to create a thread is to declare a class that
0094: * implements the <code>Runnable</code> interface. That class then
0095: * implements the <code>run</code> method. An instance of the class can
0096: * then be allocated, passed as an argument when creating
0097: * <code>Thread</code>, and started. The same example in this other
0098: * style looks like the following:
0099: * <p><hr><blockquote><pre>
0100: * class PrimeRun implements Runnable {
0101: * long minPrime;
0102: * PrimeRun(long minPrime) {
0103: * this.minPrime = minPrime;
0104: * }
0105: *
0106: * public void run() {
0107: * // compute primes larger than minPrime
0108: * . . .
0109: * }
0110: * }
0111: * </pre></blockquote><hr>
0112: * <p>
0113: * The following code would then create a thread and start it running:
0114: * <p><blockquote><pre>
0115: * PrimeRun p = new PrimeRun(143);
0116: * new Thread(p).start();
0117: * </pre></blockquote>
0118: * <p>
0119: * Every thread has a name for identification purposes. More than
0120: * one thread may have the same name. If a name is not specified when
0121: * a thread is created, a new name is generated for it.
0122: *
0123: * @author unascribed
0124: * @version 1.184, 07/30/07
0125: * @see Runnable
0126: * @see Runtime#exit(int)
0127: * @see #run()
0128: * @see #stop()
0129: * @since JDK1.0
0130: */
0131: public class Thread implements Runnable {
0132: /* Make sure registerNatives is the first thing <clinit> does. */
0133: private static native void registerNatives();
0134:
0135: static {
0136: registerNatives();
0137: }
0138:
0139: private char name[];
0140: private int priority;
0141: private Thread threadQ;
0142: private long eetop;
0143:
0144: /* Whether or not to single_step this thread. */
0145: private boolean single_step;
0146:
0147: /* Whether or not the thread is a daemon thread. */
0148: private boolean daemon = false;
0149:
0150: /* JVM state */
0151: private boolean stillborn = false;
0152:
0153: /* What will be run. */
0154: private Runnable target;
0155:
0156: /* The group of this thread */
0157: private ThreadGroup group;
0158:
0159: /* The context ClassLoader for this thread */
0160: private ClassLoader contextClassLoader;
0161:
0162: /* The inherited AccessControlContext of this thread */
0163: private AccessControlContext inheritedAccessControlContext;
0164:
0165: /* For autonumbering anonymous threads. */
0166: private static int threadInitNumber;
0167:
0168: private static synchronized int nextThreadNum() {
0169: return threadInitNumber++;
0170: }
0171:
0172: /* ThreadLocal values pertaining to this thread. This map is maintained
0173: * by the ThreadLocal class. */
0174: ThreadLocal.ThreadLocalMap threadLocals = null;
0175:
0176: /*
0177: * InheritableThreadLocal values pertaining to this thread. This map is
0178: * maintained by the InheritableThreadLocal class.
0179: */
0180: ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
0181:
0182: /*
0183: * The requested stack size for this thread, or 0 if the creator did
0184: * not specify a stack size. It is up to the VM to do whatever it
0185: * likes with this number; some VMs will ignore it.
0186: */
0187: private long stackSize;
0188:
0189: /*
0190: * JVM-private state that persists after native thread termination.
0191: */
0192: private long nativeParkEventPointer;
0193:
0194: /*
0195: * Thread ID
0196: */
0197: private long tid;
0198:
0199: /* For generating thread ID */
0200: private static long threadSeqNumber;
0201:
0202: /* Java thread status for tools,
0203: * initialized to indicate thread 'not yet started'
0204: */
0205:
0206: private int threadStatus = 0;
0207:
0208: private static synchronized long nextThreadID() {
0209: return ++threadSeqNumber;
0210: }
0211:
0212: /**
0213: * The argument supplied to the current call to
0214: * java.util.concurrent.locks.LockSupport.park.
0215: * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
0216: * Accessed using java.util.concurrent.locks.LockSupport.getBlocker
0217: */
0218: volatile Object parkBlocker;
0219:
0220: /* The object in which this thread is blocked in an interruptible I/O
0221: * operation, if any. The blocker's interrupt method should be invoked
0222: * after setting this thread's interrupt status.
0223: */
0224: private volatile Interruptible blocker;
0225: private Object blockerLock = new Object();
0226:
0227: /* Set the blocker field; invoked via sun.misc.SharedSecrets from java.nio code
0228: */
0229: void blockedOn(Interruptible b) {
0230: synchronized (blockerLock) {
0231: blocker = b;
0232: }
0233: }
0234:
0235: /**
0236: * The minimum priority that a thread can have.
0237: */
0238: public final static int MIN_PRIORITY = 1;
0239:
0240: /**
0241: * The default priority that is assigned to a thread.
0242: */
0243: public final static int NORM_PRIORITY = 5;
0244:
0245: /**
0246: * The maximum priority that a thread can have.
0247: */
0248: public final static int MAX_PRIORITY = 10;
0249:
0250: /* If stop was called before start */
0251: private boolean stopBeforeStart;
0252:
0253: /* Remembered Throwable from stop before start */
0254: private Throwable throwableFromStop;
0255:
0256: /**
0257: * Returns a reference to the currently executing thread object.
0258: *
0259: * @return the currently executing thread.
0260: */
0261: public static native Thread currentThread();
0262:
0263: /**
0264: * Causes the currently executing thread object to temporarily pause
0265: * and allow other threads to execute.
0266: */
0267: public static native void yield();
0268:
0269: /**
0270: * Causes the currently executing thread to sleep (temporarily cease
0271: * execution) for the specified number of milliseconds, subject to
0272: * the precision and accuracy of system timers and schedulers. The thread
0273: * does not lose ownership of any monitors.
0274: *
0275: * @param millis
0276: * the length of time to sleep in milliseconds
0277: *
0278: * @throws IllegalArgumentException
0279: * if the value of {@code millis} is negative
0280: *
0281: * @throws InterruptedException
0282: * if any thread has interrupted the current thread. The
0283: * <i>interrupted status</i> of the current thread is
0284: * cleared when this exception is thrown.
0285: */
0286: public static native void sleep(long millis)
0287: throws InterruptedException;
0288:
0289: /**
0290: * Causes the currently executing thread to sleep (temporarily cease
0291: * execution) for the specified number of milliseconds plus the specified
0292: * number of nanoseconds, subject to the precision and accuracy of system
0293: * timers and schedulers. The thread does not lose ownership of any
0294: * monitors.
0295: *
0296: * @param millis
0297: * the length of time to sleep in milliseconds
0298: *
0299: * @param nanos
0300: * {@code 0-999999} additional nanoseconds to sleep
0301: *
0302: * @throws IllegalArgumentException
0303: * if the value of {@code millis} is negative, or the value of
0304: * {@code nanos} is not in the range {@code 0-999999}
0305: *
0306: * @throws InterruptedException
0307: * if any thread has interrupted the current thread. The
0308: * <i>interrupted status</i> of the current thread is
0309: * cleared when this exception is thrown.
0310: */
0311: public static void sleep(long millis, int nanos)
0312: throws InterruptedException {
0313: if (millis < 0) {
0314: throw new IllegalArgumentException(
0315: "timeout value is negative");
0316: }
0317:
0318: if (nanos < 0 || nanos > 999999) {
0319: throw new IllegalArgumentException(
0320: "nanosecond timeout value out of range");
0321: }
0322:
0323: if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
0324: millis++;
0325: }
0326:
0327: sleep(millis);
0328: }
0329:
0330: /**
0331: * Initializes a Thread.
0332: *
0333: * @param g the Thread group
0334: * @param target the object whose run() method gets called
0335: * @param name the name of the new Thread
0336: * @param stackSize the desired stack size for the new thread, or
0337: * zero to indicate that this parameter is to be ignored.
0338: */
0339: private void init(ThreadGroup g, Runnable target, String name,
0340: long stackSize) {
0341: Thread parent = currentThread();
0342: SecurityManager security = System.getSecurityManager();
0343: if (g == null) {
0344: /* Determine if it's an applet or not */
0345:
0346: /* If there is a security manager, ask the security manager
0347: what to do. */
0348: if (security != null) {
0349: g = security.getThreadGroup();
0350: }
0351:
0352: /* If the security doesn't have a strong opinion of the matter
0353: use the parent thread group. */
0354: if (g == null) {
0355: g = parent.getThreadGroup();
0356: }
0357: }
0358:
0359: /* checkAccess regardless of whether or not threadgroup is
0360: explicitly passed in. */
0361: g.checkAccess();
0362:
0363: /*
0364: * Do we have the required permissions?
0365: */
0366: if (security != null) {
0367: if (isCCLOverridden(getClass())) {
0368: security
0369: .checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
0370: }
0371: }
0372:
0373: g.addUnstarted();
0374:
0375: this .group = g;
0376: this .daemon = parent.isDaemon();
0377: this .priority = parent.getPriority();
0378: this .name = name.toCharArray();
0379: if (security == null || isCCLOverridden(parent.getClass()))
0380: this .contextClassLoader = parent.getContextClassLoader();
0381: else
0382: this .contextClassLoader = parent.contextClassLoader;
0383: this .inheritedAccessControlContext = AccessController
0384: .getContext();
0385: this .target = target;
0386: setPriority(priority);
0387: if (parent.inheritableThreadLocals != null)
0388: this .inheritableThreadLocals = ThreadLocal
0389: .createInheritedMap(parent.inheritableThreadLocals);
0390: /* Stash the specified stack size in case the VM cares */
0391: this .stackSize = stackSize;
0392:
0393: /* Set thread ID */
0394: tid = nextThreadID();
0395: }
0396:
0397: /**
0398: * Allocates a new <code>Thread</code> object. This constructor has
0399: * the same effect as <code>Thread(null, null,</code>
0400: * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
0401: * a newly generated name. Automatically generated names are of the
0402: * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
0403: *
0404: * @see #Thread(ThreadGroup, Runnable, String)
0405: */
0406: public Thread() {
0407: init(null, null, "Thread-" + nextThreadNum(), 0);
0408: }
0409:
0410: /**
0411: * Allocates a new <code>Thread</code> object. This constructor has
0412: * the same effect as <code>Thread(null, target,</code>
0413: * <i>gname</i><code>)</code>, where <i>gname</i> is
0414: * a newly generated name. Automatically generated names are of the
0415: * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
0416: *
0417: * @param target the object whose <code>run</code> method is called.
0418: * @see #Thread(ThreadGroup, Runnable, String)
0419: */
0420: public Thread(Runnable target) {
0421: init(null, target, "Thread-" + nextThreadNum(), 0);
0422: }
0423:
0424: /**
0425: * Allocates a new <code>Thread</code> object. This constructor has
0426: * the same effect as <code>Thread(group, target,</code>
0427: * <i>gname</i><code>)</code>, where <i>gname</i> is
0428: * a newly generated name. Automatically generated names are of the
0429: * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
0430: *
0431: * @param group the thread group.
0432: * @param target the object whose <code>run</code> method is called.
0433: * @exception SecurityException if the current thread cannot create a
0434: * thread in the specified thread group.
0435: * @see #Thread(ThreadGroup, Runnable, String)
0436: */
0437: public Thread(ThreadGroup group, Runnable target) {
0438: init(group, target, "Thread-" + nextThreadNum(), 0);
0439: }
0440:
0441: /**
0442: * Allocates a new <code>Thread</code> object. This constructor has
0443: * the same effect as <code>Thread(null, null, name)</code>.
0444: *
0445: * @param name the name of the new thread.
0446: * @see #Thread(ThreadGroup, Runnable, String)
0447: */
0448: public Thread(String name) {
0449: init(null, null, name, 0);
0450: }
0451:
0452: /**
0453: * Allocates a new <code>Thread</code> object. This constructor has
0454: * the same effect as <code>Thread(group, null, name)</code>
0455: *
0456: * @param group the thread group.
0457: * @param name the name of the new thread.
0458: * @exception SecurityException if the current thread cannot create a
0459: * thread in the specified thread group.
0460: * @see #Thread(ThreadGroup, Runnable, String)
0461: */
0462: public Thread(ThreadGroup group, String name) {
0463: init(group, null, name, 0);
0464: }
0465:
0466: /**
0467: * Allocates a new <code>Thread</code> object. This constructor has
0468: * the same effect as <code>Thread(null, target, name)</code>.
0469: *
0470: * @param target the object whose <code>run</code> method is called.
0471: * @param name the name of the new thread.
0472: * @see #Thread(ThreadGroup, Runnable, String)
0473: */
0474: public Thread(Runnable target, String name) {
0475: init(null, target, name, 0);
0476: }
0477:
0478: /**
0479: * Allocates a new <code>Thread</code> object so that it has
0480: * <code>target</code> as its run object, has the specified
0481: * <code>name</code> as its name, and belongs to the thread group
0482: * referred to by <code>group</code>.
0483: * <p>
0484: * If <code>group</code> is <code>null</code> and there is a
0485: * security manager, the group is determined by the security manager's
0486: * <code>getThreadGroup</code> method. If <code>group</code> is
0487: * <code>null</code> and there is not a security manager, or the
0488: * security manager's <code>getThreadGroup</code> method returns
0489: * <code>null</code>, the group is set to be the same ThreadGroup
0490: * as the thread that is creating the new thread.
0491: *
0492: * <p>If there is a security manager, its <code>checkAccess</code>
0493: * method is called with the ThreadGroup as its argument.
0494: * <p>In addition, its <code>checkPermission</code>
0495: * method is called with the
0496: * <code>RuntimePermission("enableContextClassLoaderOverride")</code>
0497: * permission when invoked directly or indirectly by the constructor
0498: * of a subclass which overrides the <code>getContextClassLoader</code>
0499: * or <code>setContextClassLoader</code> methods.
0500: * This may result in a SecurityException.
0501:
0502: * <p>
0503: * If the <code>target</code> argument is not <code>null</code>, the
0504: * <code>run</code> method of the <code>target</code> is called when
0505: * this thread is started. If the target argument is
0506: * <code>null</code>, this thread's <code>run</code> method is called
0507: * when this thread is started.
0508: * <p>
0509: * The priority of the newly created thread is set equal to the
0510: * priority of the thread creating it, that is, the currently running
0511: * thread. The method <code>setPriority</code> may be used to
0512: * change the priority to a new value.
0513: * <p>
0514: * The newly created thread is initially marked as being a daemon
0515: * thread if and only if the thread creating it is currently marked
0516: * as a daemon thread. The method <code>setDaemon </code> may be used
0517: * to change whether or not a thread is a daemon.
0518: *
0519: * @param group the thread group.
0520: * @param target the object whose <code>run</code> method is called.
0521: * @param name the name of the new thread.
0522: * @exception SecurityException if the current thread cannot create a
0523: * thread in the specified thread group or cannot
0524: * override the context class loader methods.
0525: * @see Runnable#run()
0526: * @see #run()
0527: * @see #setDaemon(boolean)
0528: * @see #setPriority(int)
0529: * @see ThreadGroup#checkAccess()
0530: * @see SecurityManager#checkAccess
0531: */
0532: public Thread(ThreadGroup group, Runnable target, String name) {
0533: init(group, target, name, 0);
0534: }
0535:
0536: /**
0537: * Allocates a new <code>Thread</code> object so that it has
0538: * <code>target</code> as its run object, has the specified
0539: * <code>name</code> as its name, belongs to the thread group referred to
0540: * by <code>group</code>, and has the specified <i>stack size</i>.
0541: *
0542: * <p>This constructor is identical to {@link
0543: * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact
0544: * that it allows the thread stack size to be specified. The stack size
0545: * is the approximate number of bytes of address space that the virtual
0546: * machine is to allocate for this thread's stack. <b>The effect of the
0547: * <tt>stackSize</tt> parameter, if any, is highly platform dependent.</b>
0548: *
0549: * <p>On some platforms, specifying a higher value for the
0550: * <tt>stackSize</tt> parameter may allow a thread to achieve greater
0551: * recursion depth before throwing a {@link StackOverflowError}.
0552: * Similarly, specifying a lower value may allow a greater number of
0553: * threads to exist concurrently without throwing an {@link
0554: * OutOfMemoryError} (or other internal error). The details of
0555: * the relationship between the value of the <tt>stackSize</tt> parameter
0556: * and the maximum recursion depth and concurrency level are
0557: * platform-dependent. <b>On some platforms, the value of the
0558: * <tt>stackSize</tt> parameter may have no effect whatsoever.</b>
0559: *
0560: * <p>The virtual machine is free to treat the <tt>stackSize</tt>
0561: * parameter as a suggestion. If the specified value is unreasonably low
0562: * for the platform, the virtual machine may instead use some
0563: * platform-specific minimum value; if the specified value is unreasonably
0564: * high, the virtual machine may instead use some platform-specific
0565: * maximum. Likewise, the virtual machine is free to round the specified
0566: * value up or down as it sees fit (or to ignore it completely).
0567: *
0568: * <p>Specifying a value of zero for the <tt>stackSize</tt> parameter will
0569: * cause this constructor to behave exactly like the
0570: * <tt>Thread(ThreadGroup, Runnable, String)</tt> constructor.
0571: *
0572: * <p><i>Due to the platform-dependent nature of the behavior of this
0573: * constructor, extreme care should be exercised in its use.
0574: * The thread stack size necessary to perform a given computation will
0575: * likely vary from one JRE implementation to another. In light of this
0576: * variation, careful tuning of the stack size parameter may be required,
0577: * and the tuning may need to be repeated for each JRE implementation on
0578: * which an application is to run.</i>
0579: *
0580: * <p>Implementation note: Java platform implementers are encouraged to
0581: * document their implementation's behavior with respect to the
0582: * <tt>stackSize parameter</tt>.
0583: *
0584: * @param group the thread group.
0585: * @param target the object whose <code>run</code> method is called.
0586: * @param name the name of the new thread.
0587: * @param stackSize the desired stack size for the new thread, or
0588: * zero to indicate that this parameter is to be ignored.
0589: * @exception SecurityException if the current thread cannot create a
0590: * thread in the specified thread group.
0591: * @since 1.4
0592: */
0593: public Thread(ThreadGroup group, Runnable target, String name,
0594: long stackSize) {
0595: init(group, target, name, stackSize);
0596: }
0597:
0598: /**
0599: * Causes this thread to begin execution; the Java Virtual Machine
0600: * calls the <code>run</code> method of this thread.
0601: * <p>
0602: * The result is that two threads are running concurrently: the
0603: * current thread (which returns from the call to the
0604: * <code>start</code> method) and the other thread (which executes its
0605: * <code>run</code> method).
0606: * <p>
0607: * It is never legal to start a thread more than once.
0608: * In particular, a thread may not be restarted once it has completed
0609: * execution.
0610: *
0611: * @exception IllegalThreadStateException if the thread was already
0612: * started.
0613: * @see #run()
0614: * @see #stop()
0615: */
0616: public synchronized void start() {
0617: /**
0618: * This method is not invoked for the main method thread or "system"
0619: * group threads created/set up by the VM. Any new functionality added
0620: * to this method in the future may have to also be added to the VM.
0621: *
0622: * A zero status value corresponds to state "NEW".
0623: */
0624: if (threadStatus != 0)
0625: throw new IllegalThreadStateException();
0626: group.add(this );
0627: start0();
0628: if (stopBeforeStart) {
0629: stop0(throwableFromStop);
0630: }
0631: }
0632:
0633: private native void start0();
0634:
0635: /**
0636: * If this thread was constructed using a separate
0637: * <code>Runnable</code> run object, then that
0638: * <code>Runnable</code> object's <code>run</code> method is called;
0639: * otherwise, this method does nothing and returns.
0640: * <p>
0641: * Subclasses of <code>Thread</code> should override this method.
0642: *
0643: * @see #start()
0644: * @see #stop()
0645: * @see #Thread(ThreadGroup, Runnable, String)
0646: */
0647: public void run() {
0648: if (target != null) {
0649: target.run();
0650: }
0651: }
0652:
0653: /**
0654: * This method is called by the system to give a Thread
0655: * a chance to clean up before it actually exits.
0656: */
0657: private void exit() {
0658: if (group != null) {
0659: group.remove(this );
0660: group = null;
0661: }
0662: /* Aggressively null out all reference fields: see bug 4006245 */
0663: target = null;
0664: /* Speed the release of some of these resources */
0665: threadLocals = null;
0666: inheritableThreadLocals = null;
0667: inheritedAccessControlContext = null;
0668: blocker = null;
0669: uncaughtExceptionHandler = null;
0670: }
0671:
0672: /**
0673: * Forces the thread to stop executing.
0674: * <p>
0675: * If there is a security manager installed, its <code>checkAccess</code>
0676: * method is called with <code>this</code>
0677: * as its argument. This may result in a
0678: * <code>SecurityException</code> being raised (in the current thread).
0679: * <p>
0680: * If this thread is different from the current thread (that is, the current
0681: * thread is trying to stop a thread other than itself), the
0682: * security manager's <code>checkPermission</code> method (with a
0683: * <code>RuntimePermission("stopThread")</code> argument) is called in
0684: * addition.
0685: * Again, this may result in throwing a
0686: * <code>SecurityException</code> (in the current thread).
0687: * <p>
0688: * The thread represented by this thread is forced to stop whatever
0689: * it is doing abnormally and to throw a newly created
0690: * <code>ThreadDeath</code> object as an exception.
0691: * <p>
0692: * It is permitted to stop a thread that has not yet been started.
0693: * If the thread is eventually started, it immediately terminates.
0694: * <p>
0695: * An application should not normally try to catch
0696: * <code>ThreadDeath</code> unless it must do some extraordinary
0697: * cleanup operation (note that the throwing of
0698: * <code>ThreadDeath</code> causes <code>finally</code> clauses of
0699: * <code>try</code> statements to be executed before the thread
0700: * officially dies). If a <code>catch</code> clause catches a
0701: * <code>ThreadDeath</code> object, it is important to rethrow the
0702: * object so that the thread actually dies.
0703: * <p>
0704: * The top-level error handler that reacts to otherwise uncaught
0705: * exceptions does not print out a message or otherwise notify the
0706: * application if the uncaught exception is an instance of
0707: * <code>ThreadDeath</code>.
0708: *
0709: * @exception SecurityException if the current thread cannot
0710: * modify this thread.
0711: * @see #interrupt()
0712: * @see #checkAccess()
0713: * @see #run()
0714: * @see #start()
0715: * @see ThreadDeath
0716: * @see ThreadGroup#uncaughtException(Thread,Throwable)
0717: * @see SecurityManager#checkAccess(Thread)
0718: * @see SecurityManager#checkPermission
0719: * @deprecated This method is inherently unsafe. Stopping a thread with
0720: * Thread.stop causes it to unlock all of the monitors that it
0721: * has locked (as a natural consequence of the unchecked
0722: * <code>ThreadDeath</code> exception propagating up the stack). If
0723: * any of the objects previously protected by these monitors were in
0724: * an inconsistent state, the damaged objects become visible to
0725: * other threads, potentially resulting in arbitrary behavior. Many
0726: * uses of <code>stop</code> should be replaced by code that simply
0727: * modifies some variable to indicate that the target thread should
0728: * stop running. The target thread should check this variable
0729: * regularly, and return from its run method in an orderly fashion
0730: * if the variable indicates that it is to stop running. If the
0731: * target thread waits for long periods (on a condition variable,
0732: * for example), the <code>interrupt</code> method should be used to
0733: * interrupt the wait.
0734: * For more information, see
0735: * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
0736: * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
0737: */
0738: @Deprecated
0739: public final void stop() {
0740: // If the thread is already dead, return.
0741: // A zero status value corresponds to "NEW".
0742: if ((threadStatus != 0) && !isAlive()) {
0743: return;
0744: }
0745: stop1(new ThreadDeath());
0746: }
0747:
0748: /**
0749: * Forces the thread to stop executing.
0750: * <p>
0751: * If there is a security manager installed, the <code>checkAccess</code>
0752: * method of this thread is called, which may result in a
0753: * <code>SecurityException</code> being raised (in the current thread).
0754: * <p>
0755: * If this thread is different from the current thread (that is, the current
0756: * thread is trying to stop a thread other than itself) or
0757: * <code>obj</code> is not an instance of <code>ThreadDeath</code>, the
0758: * security manager's <code>checkPermission</code> method (with the
0759: * <code>RuntimePermission("stopThread")</code> argument) is called in
0760: * addition.
0761: * Again, this may result in throwing a
0762: * <code>SecurityException</code> (in the current thread).
0763: * <p>
0764: * If the argument <code>obj</code> is null, a
0765: * <code>NullPointerException</code> is thrown (in the current thread).
0766: * <p>
0767: * The thread represented by this thread is forced to stop
0768: * whatever it is doing abnormally and to throw the
0769: * <code>Throwable</code> object <code>obj</code> as an exception. This
0770: * is an unusual action to take; normally, the <code>stop</code> method
0771: * that takes no arguments should be used.
0772: * <p>
0773: * It is permitted to stop a thread that has not yet been started.
0774: * If the thread is eventually started, it immediately terminates.
0775: *
0776: * @param obj the Throwable object to be thrown.
0777: * @exception SecurityException if the current thread cannot modify
0778: * this thread.
0779: * @throws NullPointerException if obj is <tt>null</tt>.
0780: * @see #interrupt()
0781: * @see #checkAccess()
0782: * @see #run()
0783: * @see #start()
0784: * @see #stop()
0785: * @see SecurityManager#checkAccess(Thread)
0786: * @see SecurityManager#checkPermission
0787: * @deprecated This method is inherently unsafe. See {@link #stop()}
0788: * for details. An additional danger of this
0789: * method is that it may be used to generate exceptions that the
0790: * target thread is unprepared to handle (including checked
0791: * exceptions that the thread could not possibly throw, were it
0792: * not for this method).
0793: * For more information, see
0794: * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
0795: * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
0796: */
0797: @Deprecated
0798: public final synchronized void stop(Throwable obj) {
0799: stop1(obj);
0800: }
0801:
0802: /**
0803: * Common impl for stop() and stop(Throwable).
0804: */
0805: private final synchronized void stop1(Throwable th) {
0806: SecurityManager security = System.getSecurityManager();
0807: if (security != null) {
0808: checkAccess();
0809: if ((this != Thread.currentThread())
0810: || (!(th instanceof ThreadDeath))) {
0811: security
0812: .checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
0813: }
0814: }
0815: // A zero status value corresponds to "NEW"
0816: if (threadStatus != 0) {
0817: resume(); // Wake up thread if it was suspended; no-op otherwise
0818: stop0(th);
0819: } else {
0820:
0821: // Must do the null arg check that the VM would do with stop0
0822: if (th == null) {
0823: throw new NullPointerException();
0824: }
0825:
0826: // Remember this stop attempt for if/when start is used
0827: stopBeforeStart = true;
0828: throwableFromStop = th;
0829: }
0830: }
0831:
0832: /**
0833: * Interrupts this thread.
0834: *
0835: * <p> Unless the current thread is interrupting itself, which is
0836: * always permitted, the {@link #checkAccess() checkAccess} method
0837: * of this thread is invoked, which may cause a {@link
0838: * SecurityException} to be thrown.
0839: *
0840: * <p> If this thread is blocked in an invocation of the {@link
0841: * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
0842: * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
0843: * class, or of the {@link #join()}, {@link #join(long)}, {@link
0844: * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
0845: * methods of this class, then its interrupt status will be cleared and it
0846: * will receive an {@link InterruptedException}.
0847: *
0848: * <p> If this thread is blocked in an I/O operation upon an {@link
0849: * java.nio.channels.InterruptibleChannel </code>interruptible
0850: * channel<code>} then the channel will be closed, the thread's interrupt
0851: * status will be set, and the thread will receive a {@link
0852: * java.nio.channels.ClosedByInterruptException}.
0853: *
0854: * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
0855: * then the thread's interrupt status will be set and it will return
0856: * immediately from the selection operation, possibly with a non-zero
0857: * value, just as if the selector's {@link
0858: * java.nio.channels.Selector#wakeup wakeup} method were invoked.
0859: *
0860: * <p> If none of the previous conditions hold then this thread's interrupt
0861: * status will be set. </p>
0862: *
0863: * <p> Interrupting a thread that is not alive need not have any effect.
0864: *
0865: * @throws SecurityException
0866: * if the current thread cannot modify this thread
0867: *
0868: * @revised 6.0
0869: * @spec JSR-51
0870: */
0871: public void interrupt() {
0872: if (this != Thread.currentThread())
0873: checkAccess();
0874:
0875: synchronized (blockerLock) {
0876: Interruptible b = blocker;
0877: if (b != null) {
0878: interrupt0(); // Just to set the interrupt flag
0879: b.interrupt();
0880: return;
0881: }
0882: }
0883: interrupt0();
0884: }
0885:
0886: /**
0887: * Tests whether the current thread has been interrupted. The
0888: * <i>interrupted status</i> of the thread is cleared by this method. In
0889: * other words, if this method were to be called twice in succession, the
0890: * second call would return false (unless the current thread were
0891: * interrupted again, after the first call had cleared its interrupted
0892: * status and before the second call had examined it).
0893: *
0894: * <p>A thread interruption ignored because a thread was not alive
0895: * at the time of the interrupt will be reflected by this method
0896: * returning false.
0897: *
0898: * @return <code>true</code> if the current thread has been interrupted;
0899: * <code>false</code> otherwise.
0900: * @see #isInterrupted()
0901: * @revised 6.0
0902: */
0903: public static boolean interrupted() {
0904: return currentThread().isInterrupted(true);
0905: }
0906:
0907: /**
0908: * Tests whether this thread has been interrupted. The <i>interrupted
0909: * status</i> of the thread is unaffected by this method.
0910: *
0911: * <p>A thread interruption ignored because a thread was not alive
0912: * at the time of the interrupt will be reflected by this method
0913: * returning false.
0914: *
0915: * @return <code>true</code> if this thread has been interrupted;
0916: * <code>false</code> otherwise.
0917: * @see #interrupted()
0918: * @revised 6.0
0919: */
0920: public boolean isInterrupted() {
0921: return isInterrupted(false);
0922: }
0923:
0924: /**
0925: * Tests if some Thread has been interrupted. The interrupted state
0926: * is reset or not based on the value of ClearInterrupted that is
0927: * passed.
0928: */
0929: private native boolean isInterrupted(boolean ClearInterrupted);
0930:
0931: /**
0932: * Throws {@link NoSuchMethodError}.
0933: *
0934: * @deprecated This method was originally designed to destroy this
0935: * thread without any cleanup. Any monitors it held would have
0936: * remained locked. However, the method was never implemented.
0937: * If if were to be implemented, it would be deadlock-prone in
0938: * much the manner of {@link #suspend}. If the target thread held
0939: * a lock protecting a critical system resource when it was
0940: * destroyed, no thread could ever access this resource again.
0941: * If another thread ever attempted to lock this resource, deadlock
0942: * would result. Such deadlocks typically manifest themselves as
0943: * "frozen" processes. For more information, see
0944: * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">
0945: * Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
0946: * @throws NoSuchMethodError always
0947: */
0948: @Deprecated
0949: public void destroy() {
0950: throw new NoSuchMethodError();
0951: }
0952:
0953: /**
0954: * Tests if this thread is alive. A thread is alive if it has
0955: * been started and has not yet died.
0956: *
0957: * @return <code>true</code> if this thread is alive;
0958: * <code>false</code> otherwise.
0959: */
0960: public final native boolean isAlive();
0961:
0962: /**
0963: * Suspends this thread.
0964: * <p>
0965: * First, the <code>checkAccess</code> method of this thread is called
0966: * with no arguments. This may result in throwing a
0967: * <code>SecurityException </code>(in the current thread).
0968: * <p>
0969: * If the thread is alive, it is suspended and makes no further
0970: * progress unless and until it is resumed.
0971: *
0972: * @exception SecurityException if the current thread cannot modify
0973: * this thread.
0974: * @see #checkAccess
0975: * @deprecated This method has been deprecated, as it is
0976: * inherently deadlock-prone. If the target thread holds a lock on the
0977: * monitor protecting a critical system resource when it is suspended, no
0978: * thread can access this resource until the target thread is resumed. If
0979: * the thread that would resume the target thread attempts to lock this
0980: * monitor prior to calling <code>resume</code>, deadlock results. Such
0981: * deadlocks typically manifest themselves as "frozen" processes.
0982: * For more information, see
0983: * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
0984: * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
0985: */
0986: @Deprecated
0987: public final void suspend() {
0988: checkAccess();
0989: suspend0();
0990: }
0991:
0992: /**
0993: * Resumes a suspended thread.
0994: * <p>
0995: * First, the <code>checkAccess</code> method of this thread is called
0996: * with no arguments. This may result in throwing a
0997: * <code>SecurityException</code> (in the current thread).
0998: * <p>
0999: * If the thread is alive but suspended, it is resumed and is
1000: * permitted to make progress in its execution.
1001: *
1002: * @exception SecurityException if the current thread cannot modify this
1003: * thread.
1004: * @see #checkAccess
1005: * @see #suspend()
1006: * @deprecated This method exists solely for use with {@link #suspend},
1007: * which has been deprecated because it is deadlock-prone.
1008: * For more information, see
1009: * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
1010: * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1011: */
1012: @Deprecated
1013: public final void resume() {
1014: checkAccess();
1015: resume0();
1016: }
1017:
1018: /**
1019: * Changes the priority of this thread.
1020: * <p>
1021: * First the <code>checkAccess</code> method of this thread is called
1022: * with no arguments. This may result in throwing a
1023: * <code>SecurityException</code>.
1024: * <p>
1025: * Otherwise, the priority of this thread is set to the smaller of
1026: * the specified <code>newPriority</code> and the maximum permitted
1027: * priority of the thread's thread group.
1028: *
1029: * @param newPriority priority to set this thread to
1030: * @exception IllegalArgumentException If the priority is not in the
1031: * range <code>MIN_PRIORITY</code> to
1032: * <code>MAX_PRIORITY</code>.
1033: * @exception SecurityException if the current thread cannot modify
1034: * this thread.
1035: * @see #getPriority
1036: * @see #checkAccess()
1037: * @see #getThreadGroup()
1038: * @see #MAX_PRIORITY
1039: * @see #MIN_PRIORITY
1040: * @see ThreadGroup#getMaxPriority()
1041: */
1042: public final void setPriority(int newPriority) {
1043: ThreadGroup g;
1044: checkAccess();
1045: if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
1046: throw new IllegalArgumentException();
1047: }
1048: if ((g = getThreadGroup()) != null) {
1049: if (newPriority > g.getMaxPriority()) {
1050: newPriority = g.getMaxPriority();
1051: }
1052: setPriority0(priority = newPriority);
1053: }
1054: }
1055:
1056: /**
1057: * Returns this thread's priority.
1058: *
1059: * @return this thread's priority.
1060: * @see #setPriority
1061: */
1062: public final int getPriority() {
1063: return priority;
1064: }
1065:
1066: /**
1067: * Changes the name of this thread to be equal to the argument
1068: * <code>name</code>.
1069: * <p>
1070: * First the <code>checkAccess</code> method of this thread is called
1071: * with no arguments. This may result in throwing a
1072: * <code>SecurityException</code>.
1073: *
1074: * @param name the new name for this thread.
1075: * @exception SecurityException if the current thread cannot modify this
1076: * thread.
1077: * @see #getName
1078: * @see #checkAccess()
1079: */
1080: public final void setName(String name) {
1081: checkAccess();
1082: this .name = name.toCharArray();
1083: }
1084:
1085: /**
1086: * Returns this thread's name.
1087: *
1088: * @return this thread's name.
1089: * @see #setName(String)
1090: */
1091: public final String getName() {
1092: return String.valueOf(name);
1093: }
1094:
1095: /**
1096: * Returns the thread group to which this thread belongs.
1097: * This method returns null if this thread has died
1098: * (been stopped).
1099: *
1100: * @return this thread's thread group.
1101: */
1102: public final ThreadGroup getThreadGroup() {
1103: return group;
1104: }
1105:
1106: /**
1107: * Returns the number of active threads in the current thread's thread
1108: * group.
1109: *
1110: * @return the number of active threads in the current thread's thread
1111: * group.
1112: */
1113: public static int activeCount() {
1114: return currentThread().getThreadGroup().activeCount();
1115: }
1116:
1117: /**
1118: * Copies into the specified array every active thread in
1119: * the current thread's thread group and its subgroups. This method simply
1120: * calls the <code>enumerate</code> method of the current thread's thread
1121: * group with the array argument.
1122: * <p>
1123: * First, if there is a security manager, that <code>enumerate</code>
1124: * method calls the security
1125: * manager's <code>checkAccess</code> method
1126: * with the thread group as its argument. This may result
1127: * in throwing a <code>SecurityException</code>.
1128: *
1129: * @param tarray an array of Thread objects to copy to
1130: * @return the number of threads put into the array
1131: * @exception SecurityException if a security manager exists and its
1132: * <code>checkAccess</code> method doesn't allow the operation.
1133: * @see ThreadGroup#enumerate(Thread[])
1134: * @see SecurityManager#checkAccess(ThreadGroup)
1135: */
1136: public static int enumerate(Thread tarray[]) {
1137: return currentThread().getThreadGroup().enumerate(tarray);
1138: }
1139:
1140: /**
1141: * Counts the number of stack frames in this thread. The thread must
1142: * be suspended.
1143: *
1144: * @return the number of stack frames in this thread.
1145: * @exception IllegalThreadStateException if this thread is not
1146: * suspended.
1147: * @deprecated The definition of this call depends on {@link #suspend},
1148: * which is deprecated. Further, the results of this call
1149: * were never well-defined.
1150: */
1151: @Deprecated
1152: public native int countStackFrames();
1153:
1154: /**
1155: * Waits at most {@code millis} milliseconds for this thread to
1156: * die. A timeout of {@code 0} means to wait forever.
1157: *
1158: * <p> This implementation uses a loop of {@code this.wait} calls
1159: * conditioned on {@code this.isAlive}. As a thread terminates the
1160: * {@code this.notifyAll} method is invoked. It is recommended that
1161: * applications not use {@code wait}, {@code notify}, or
1162: * {@code notifyAll} on {@code Thread} instances.
1163: *
1164: * @param millis
1165: * the time to wait in milliseconds
1166: *
1167: * @throws IllegalArgumentException
1168: * if the value of {@code millis} is negative
1169: *
1170: * @throws InterruptedException
1171: * if any thread has interrupted the current thread. The
1172: * <i>interrupted status</i> of the current thread is
1173: * cleared when this exception is thrown.
1174: */
1175: public final synchronized void join(long millis)
1176: throws InterruptedException {
1177: long base = System.currentTimeMillis();
1178: long now = 0;
1179:
1180: if (millis < 0) {
1181: throw new IllegalArgumentException(
1182: "timeout value is negative");
1183: }
1184:
1185: if (millis == 0) {
1186: while (isAlive()) {
1187: wait(0);
1188: }
1189: } else {
1190: while (isAlive()) {
1191: long delay = millis - now;
1192: if (delay <= 0) {
1193: break;
1194: }
1195: wait(delay);
1196: now = System.currentTimeMillis() - base;
1197: }
1198: }
1199: }
1200:
1201: /**
1202: * Waits at most {@code millis} milliseconds plus
1203: * {@code nanos} nanoseconds for this thread to die.
1204: *
1205: * <p> This implementation uses a loop of {@code this.wait} calls
1206: * conditioned on {@code this.isAlive}. As a thread terminates the
1207: * {@code this.notifyAll} method is invoked. It is recommended that
1208: * applications not use {@code wait}, {@code notify}, or
1209: * {@code notifyAll} on {@code Thread} instances.
1210: *
1211: * @param millis
1212: * the time to wait in milliseconds
1213: *
1214: * @param nanos
1215: * {@code 0-999999} additional nanoseconds to wait
1216: *
1217: * @throws IllegalArgumentException
1218: * if the value of {@code millis} is negative, or the value
1219: * of {@code nanos} is not in the range {@code 0-999999}
1220: *
1221: * @throws InterruptedException
1222: * if any thread has interrupted the current thread. The
1223: * <i>interrupted status</i> of the current thread is
1224: * cleared when this exception is thrown.
1225: */
1226: public final synchronized void join(long millis, int nanos)
1227: throws InterruptedException {
1228:
1229: if (millis < 0) {
1230: throw new IllegalArgumentException(
1231: "timeout value is negative");
1232: }
1233:
1234: if (nanos < 0 || nanos > 999999) {
1235: throw new IllegalArgumentException(
1236: "nanosecond timeout value out of range");
1237: }
1238:
1239: if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
1240: millis++;
1241: }
1242:
1243: join(millis);
1244: }
1245:
1246: /**
1247: * Waits for this thread to die.
1248: *
1249: * <p> An invocation of this method behaves in exactly the same
1250: * way as the invocation
1251: *
1252: * <blockquote>
1253: * {@linkplain #join(long) join}{@code (0)}
1254: * </blockquote>
1255: *
1256: * @throws InterruptedException
1257: * if any thread has interrupted the current thread. The
1258: * <i>interrupted status</i> of the current thread is
1259: * cleared when this exception is thrown.
1260: */
1261: public final void join() throws InterruptedException {
1262: join(0);
1263: }
1264:
1265: /**
1266: * Prints a stack trace of the current thread to the standard error stream.
1267: * This method is used only for debugging.
1268: *
1269: * @see Throwable#printStackTrace()
1270: */
1271: public static void dumpStack() {
1272: new Exception("Stack trace").printStackTrace();
1273: }
1274:
1275: /**
1276: * Marks this thread as either a {@linkplain #isDaemon daemon} thread
1277: * or a user thread. The Java Virtual Machine exits when the only
1278: * threads running are all daemon threads.
1279: *
1280: * <p> This method must be invoked before the thread is started.
1281: *
1282: * @param on
1283: * if {@code true}, marks this thread as a daemon thread
1284: *
1285: * @throws IllegalThreadStateException
1286: * if this thread is {@linkplain #isAlive alive}
1287: *
1288: * @throws SecurityException
1289: * if {@link #checkAccess} determines that the current
1290: * thread cannot modify this thread
1291: */
1292: public final void setDaemon(boolean on) {
1293: checkAccess();
1294: if (isAlive()) {
1295: throw new IllegalThreadStateException();
1296: }
1297: daemon = on;
1298: }
1299:
1300: /**
1301: * Tests if this thread is a daemon thread.
1302: *
1303: * @return <code>true</code> if this thread is a daemon thread;
1304: * <code>false</code> otherwise.
1305: * @see #setDaemon(boolean)
1306: */
1307: public final boolean isDaemon() {
1308: return daemon;
1309: }
1310:
1311: /**
1312: * Determines if the currently running thread has permission to
1313: * modify this thread.
1314: * <p>
1315: * If there is a security manager, its <code>checkAccess</code> method
1316: * is called with this thread as its argument. This may result in
1317: * throwing a <code>SecurityException</code>.
1318: *
1319: * @exception SecurityException if the current thread is not allowed to
1320: * access this thread.
1321: * @see SecurityManager#checkAccess(Thread)
1322: */
1323: public final void checkAccess() {
1324: SecurityManager security = System.getSecurityManager();
1325: if (security != null) {
1326: security.checkAccess(this );
1327: }
1328: }
1329:
1330: /**
1331: * Returns a string representation of this thread, including the
1332: * thread's name, priority, and thread group.
1333: *
1334: * @return a string representation of this thread.
1335: */
1336: public String toString() {
1337: ThreadGroup group = getThreadGroup();
1338: if (group != null) {
1339: return "Thread[" + getName() + "," + getPriority() + ","
1340: + group.getName() + "]";
1341: } else {
1342: return "Thread[" + getName() + "," + getPriority() + ","
1343: + "" + "]";
1344: }
1345: }
1346:
1347: /**
1348: * Returns the context ClassLoader for this Thread. The context
1349: * ClassLoader is provided by the creator of the thread for use
1350: * by code running in this thread when loading classes and resources.
1351: * If not set, the default is the ClassLoader context of the parent
1352: * Thread. The context ClassLoader of the primordial thread is
1353: * typically set to the class loader used to load the application.
1354: *
1355: * <p>First, if there is a security manager, and the caller's class
1356: * loader is not null and the caller's class loader is not the same as or
1357: * an ancestor of the context class loader for the thread whose
1358: * context class loader is being requested, then the security manager's
1359: * <code>checkPermission</code>
1360: * method is called with a
1361: * <code>RuntimePermission("getClassLoader")</code> permission
1362: * to see if it's ok to get the context ClassLoader..
1363: *
1364: * @return the context ClassLoader for this Thread
1365: *
1366: * @throws SecurityException
1367: * if a security manager exists and its
1368: * <code>checkPermission</code> method doesn't allow
1369: * getting the context ClassLoader.
1370: * @see #setContextClassLoader
1371: * @see SecurityManager#checkPermission
1372: * @see RuntimePermission
1373: *
1374: * @since 1.2
1375: */
1376: public ClassLoader getContextClassLoader() {
1377: if (contextClassLoader == null)
1378: return null;
1379: SecurityManager sm = System.getSecurityManager();
1380: if (sm != null) {
1381: ClassLoader ccl = ClassLoader.getCallerClassLoader();
1382: if (ccl != null && ccl != contextClassLoader
1383: && !contextClassLoader.isAncestor(ccl)) {
1384: sm
1385: .checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
1386: }
1387: }
1388: return contextClassLoader;
1389: }
1390:
1391: /**
1392: * Sets the context ClassLoader for this Thread. The context
1393: * ClassLoader can be set when a thread is created, and allows
1394: * the creator of the thread to provide the appropriate class loader
1395: * to code running in the thread when loading classes and resources.
1396: *
1397: * <p>First, if there is a security manager, its <code>checkPermission</code>
1398: * method is called with a
1399: * <code>RuntimePermission("setContextClassLoader")</code> permission
1400: * to see if it's ok to set the context ClassLoader..
1401: *
1402: * @param cl the context ClassLoader for this Thread
1403: *
1404: * @exception SecurityException if the current thread cannot set the
1405: * context ClassLoader.
1406: * @see #getContextClassLoader
1407: * @see SecurityManager#checkPermission
1408: * @see RuntimePermission
1409: *
1410: * @since 1.2
1411: */
1412: public void setContextClassLoader(ClassLoader cl) {
1413: SecurityManager sm = System.getSecurityManager();
1414: if (sm != null) {
1415: sm.checkPermission(new RuntimePermission(
1416: "setContextClassLoader"));
1417: }
1418: contextClassLoader = cl;
1419: }
1420:
1421: /**
1422: * Returns <tt>true</tt> if and only if the current thread holds the
1423: * monitor lock on the specified object.
1424: *
1425: * <p>This method is designed to allow a program to assert that
1426: * the current thread already holds a specified lock:
1427: * <pre>
1428: * assert Thread.holdsLock(obj);
1429: * </pre>
1430: *
1431: * @param obj the object on which to test lock ownership
1432: * @throws NullPointerException if obj is <tt>null</tt>
1433: * @return <tt>true</tt> if the current thread holds the monitor lock on
1434: * the specified object.
1435: * @since 1.4
1436: */
1437: public static native boolean holdsLock(Object obj);
1438:
1439: private static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0];
1440:
1441: /**
1442: * Returns an array of stack trace elements representing the stack dump
1443: * of this thread. This method will return a zero-length array if
1444: * this thread has not started, has started but has not yet been
1445: * scheduled to run by the system, or has terminated.
1446: * If the returned array is of non-zero length then the first element of
1447: * the array represents the top of the stack, which is the most recent
1448: * method invocation in the sequence. The last element of the array
1449: * represents the bottom of the stack, which is the least recent method
1450: * invocation in the sequence.
1451: *
1452: * <p>If there is a security manager, and this thread is not
1453: * the current thread, then the security manager's
1454: * <tt>checkPermission</tt> method is called with a
1455: * <tt>RuntimePermission("getStackTrace")</tt> permission
1456: * to see if it's ok to get the stack trace.
1457: *
1458: * <p>Some virtual machines may, under some circumstances, omit one
1459: * or more stack frames from the stack trace. In the extreme case,
1460: * a virtual machine that has no stack trace information concerning
1461: * this thread is permitted to return a zero-length array from this
1462: * method.
1463: *
1464: * @return an array of <tt>StackTraceElement</tt>,
1465: * each represents one stack frame.
1466: *
1467: * @throws SecurityException
1468: * if a security manager exists and its
1469: * <tt>checkPermission</tt> method doesn't allow
1470: * getting the stack trace of thread.
1471: * @see SecurityManager#checkPermission
1472: * @see RuntimePermission
1473: * @see Throwable#getStackTrace
1474: *
1475: * @since 1.5
1476: */
1477: public StackTraceElement[] getStackTrace() {
1478: if (this != Thread.currentThread()) {
1479: // check for getStackTrace permission
1480: SecurityManager security = System.getSecurityManager();
1481: if (security != null) {
1482: security
1483: .checkPermission(SecurityConstants.GET_STACK_TRACE_PERMISSION);
1484: }
1485: // optimization so we do not call into the vm for threads that
1486: // have not yet started or have terminated
1487: if (!isAlive()) {
1488: return EMPTY_STACK_TRACE;
1489: }
1490: StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] { this });
1491: StackTraceElement[] stackTrace = stackTraceArray[0];
1492: // a thread that was alive during the previous isAlive call may have
1493: // since terminated, therefore not having a stacktrace.
1494: if (stackTrace == null) {
1495: stackTrace = EMPTY_STACK_TRACE;
1496: }
1497: return stackTrace;
1498: } else {
1499: // Don't need JVM help for current thread
1500: return (new Exception()).getStackTrace();
1501: }
1502: }
1503:
1504: /**
1505: * Returns a map of stack traces for all live threads.
1506: * The map keys are threads and each map value is an array of
1507: * <tt>StackTraceElement</tt> that represents the stack dump
1508: * of the corresponding <tt>Thread</tt>.
1509: * The returned stack traces are in the format specified for
1510: * the {@link #getStackTrace getStackTrace} method.
1511: *
1512: * <p>The threads may be executing while this method is called.
1513: * The stack trace of each thread only represents a snapshot and
1514: * each stack trace may be obtained at different time. A zero-length
1515: * array will be returned in the map value if the virtual machine has
1516: * no stack trace information about a thread.
1517: *
1518: * <p>If there is a security manager, then the security manager's
1519: * <tt>checkPermission</tt> method is called with a
1520: * <tt>RuntimePermission("getStackTrace")</tt> permission as well as
1521: * <tt>RuntimePermission("modifyThreadGroup")</tt> permission
1522: * to see if it is ok to get the stack trace of all threads.
1523: *
1524: * @return a <tt>Map</tt> from <tt>Thread</tt> to an array of
1525: * <tt>StackTraceElement</tt> that represents the stack trace of
1526: * the corresponding thread.
1527: *
1528: * @throws SecurityException
1529: * if a security manager exists and its
1530: * <tt>checkPermission</tt> method doesn't allow
1531: * getting the stack trace of thread.
1532: * @see #getStackTrace
1533: * @see SecurityManager#checkPermission
1534: * @see RuntimePermission
1535: * @see Throwable#getStackTrace
1536: *
1537: * @since 1.5
1538: */
1539: public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
1540: // check for getStackTrace permission
1541: SecurityManager security = System.getSecurityManager();
1542: if (security != null) {
1543: security
1544: .checkPermission(SecurityConstants.GET_STACK_TRACE_PERMISSION);
1545: security
1546: .checkPermission(SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
1547: }
1548:
1549: // Get a snapshot of the list of all threads
1550: Thread[] threads = getThreads();
1551: StackTraceElement[][] traces = dumpThreads(threads);
1552: Map<Thread, StackTraceElement[]> m = new HashMap<Thread, StackTraceElement[]>(
1553: threads.length);
1554: for (int i = 0; i < threads.length; i++) {
1555: StackTraceElement[] stackTrace = traces[i];
1556: if (stackTrace != null) {
1557: m.put(threads[i], stackTrace);
1558: }
1559: // else terminated so we don't put it in the map
1560: }
1561: return m;
1562: }
1563:
1564: private static final RuntimePermission SUBCLASS_IMPLEMENTATION_PERMISSION = new RuntimePermission(
1565: "enableContextClassLoaderOverride");
1566:
1567: /** cache of subclass security audit results */
1568: private static final SoftCache subclassAudits = new SoftCache(10);
1569:
1570: /**
1571: * Verifies that this (possibly subclass) instance can be constructed
1572: * without violating security constraints: the subclass must not override
1573: * security-sensitive non-final methods, or else the
1574: * "enableContextClassLoaderOverride" RuntimePermission is checked.
1575: */
1576: private static boolean isCCLOverridden(Class cl) {
1577: if (cl == Thread.class)
1578: return false;
1579: Boolean result = null;
1580: synchronized (subclassAudits) {
1581: result = (Boolean) subclassAudits.get(cl);
1582: if (result == null) {
1583: /*
1584: * Note: only new Boolean instances (i.e., not Boolean.TRUE or
1585: * Boolean.FALSE) must be used as cache values, otherwise cache
1586: * entry will pin associated class.
1587: */
1588: result = new Boolean(auditSubclass(cl));
1589: subclassAudits.put(cl, result);
1590: }
1591: }
1592: return result.booleanValue();
1593: }
1594:
1595: /**
1596: * Performs reflective checks on given subclass to verify that it doesn't
1597: * override security-sensitive non-final methods. Returns true if the
1598: * subclass overrides any of the methods, false otherwise.
1599: */
1600: private static boolean auditSubclass(final Class subcl) {
1601: Boolean result = (Boolean) AccessController
1602: .doPrivileged(new PrivilegedAction() {
1603: public Object run() {
1604: for (Class cl = subcl; cl != Thread.class; cl = cl
1605: .getSuperclass()) {
1606: try {
1607: cl.getDeclaredMethod(
1608: "getContextClassLoader",
1609: new Class[0]);
1610: return Boolean.TRUE;
1611: } catch (NoSuchMethodException ex) {
1612: }
1613: try {
1614: Class[] params = { ClassLoader.class };
1615: cl
1616: .getDeclaredMethod(
1617: "setContextClassLoader",
1618: params);
1619: return Boolean.TRUE;
1620: } catch (NoSuchMethodException ex) {
1621: }
1622: }
1623: return Boolean.FALSE;
1624: }
1625: });
1626: return result.booleanValue();
1627: }
1628:
1629: private native static StackTraceElement[][] dumpThreads(
1630: Thread[] threads);
1631:
1632: private native static Thread[] getThreads();
1633:
1634: /**
1635: * Returns the identifier of this Thread. The thread ID is a positive
1636: * <tt>long</tt> number generated when this thread was created.
1637: * The thread ID is unique and remains unchanged during its lifetime.
1638: * When a thread is terminated, this thread ID may be reused.
1639: *
1640: * @return this thread's ID.
1641: * @since 1.5
1642: */
1643: public long getId() {
1644: return tid;
1645: }
1646:
1647: /**
1648: * A thread state. A thread can be in one of the following states:
1649: * <ul>
1650: * <li>{@link #NEW}<br>
1651: * A thread that has not yet started is in this state.
1652: * </li>
1653: * <li>{@link #RUNNABLE}<br>
1654: * A thread executing in the Java virtual machine is in this state.
1655: * </li>
1656: * <li>{@link #BLOCKED}<br>
1657: * A thread that is blocked waiting for a monitor lock
1658: * is in this state.
1659: * </li>
1660: * <li>{@link #WAITING}<br>
1661: * A thread that is waiting indefinitely for another thread to
1662: * perform a particular action is in this state.
1663: * </li>
1664: * <li>{@link #TIMED_WAITING}<br>
1665: * A thread that is waiting for another thread to perform an action
1666: * for up to a specified waiting time is in this state.
1667: * </li>
1668: * <li>{@link #TERMINATED}<br>
1669: * A thread that has exited is in this state.
1670: * </li>
1671: * </ul>
1672: *
1673: * <p>
1674: * A thread can be in only one state at a given point in time.
1675: * These states are virtual machine states which do not reflect
1676: * any operating system thread states.
1677: *
1678: * @since 1.5
1679: * @see #getState
1680: */
1681: public enum State {
1682: /**
1683: * Thread state for a thread which has not yet started.
1684: */
1685: NEW,
1686:
1687: /**
1688: * Thread state for a runnable thread. A thread in the runnable
1689: * state is executing in the Java virtual machine but it may
1690: * be waiting for other resources from the operating system
1691: * such as processor.
1692: */
1693: RUNNABLE,
1694:
1695: /**
1696: * Thread state for a thread blocked waiting for a monitor lock.
1697: * A thread in the blocked state is waiting for a monitor lock
1698: * to enter a synchronized block/method or
1699: * reenter a synchronized block/method after calling
1700: * {@link Object#wait() Object.wait}.
1701: */
1702: BLOCKED,
1703:
1704: /**
1705: * Thread state for a waiting thread.
1706: * A thread is in the waiting state due to calling one of the
1707: * following methods:
1708: * <ul>
1709: * <li>{@link Object#wait() Object.wait} with no timeout</li>
1710: * <li>{@link #join() Thread.join} with no timeout</li>
1711: * <li>{@link LockSupport#park() LockSupport.park}</li>
1712: * </ul>
1713: *
1714: * <p>A thread in the waiting state is waiting for another thread to
1715: * perform a particular action.
1716: *
1717: * For example, a thread that has called <tt>Object.wait()</tt>
1718: * on an object is waiting for another thread to call
1719: * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
1720: * that object. A thread that has called <tt>Thread.join()</tt>
1721: * is waiting for a specified thread to terminate.
1722: */
1723: WAITING,
1724:
1725: /**
1726: * Thread state for a waiting thread with a specified waiting time.
1727: * A thread is in the timed waiting state due to calling one of
1728: * the following methods with a specified positive waiting time:
1729: * <ul>
1730: * <li>{@link #sleep Thread.sleep}</li>
1731: * <li>{@link Object#wait(long) Object.wait} with timeout</li>
1732: * <li>{@link #join(long) Thread.join} with timeout</li>
1733: * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
1734: * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
1735: * </ul>
1736: */
1737: TIMED_WAITING,
1738:
1739: /**
1740: * Thread state for a terminated thread.
1741: * The thread has completed execution.
1742: */
1743: TERMINATED;
1744: }
1745:
1746: /**
1747: * Returns the state of this thread.
1748: * This method is designed for use in monitoring of the system state,
1749: * not for synchronization control.
1750: *
1751: * @return this thread's state.
1752: * @since 1.5
1753: */
1754: public State getState() {
1755: // get current thread state
1756: return sun.misc.VM.toThreadState(threadStatus);
1757: }
1758:
1759: // Added in JSR-166
1760:
1761: /**
1762: * Interface for handlers invoked when a <tt>Thread</tt> abruptly
1763: * terminates due to an uncaught exception.
1764: * <p>When a thread is about to terminate due to an uncaught exception
1765: * the Java Virtual Machine will query the thread for its
1766: * <tt>UncaughtExceptionHandler</tt> using
1767: * {@link #getUncaughtExceptionHandler} and will invoke the handler's
1768: * <tt>uncaughtException</tt> method, passing the thread and the
1769: * exception as arguments.
1770: * If a thread has not had its <tt>UncaughtExceptionHandler</tt>
1771: * explicitly set, then its <tt>ThreadGroup</tt> object acts as its
1772: * <tt>UncaughtExceptionHandler</tt>. If the <tt>ThreadGroup</tt> object
1773: * has no
1774: * special requirements for dealing with the exception, it can forward
1775: * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
1776: * default uncaught exception handler}.
1777: *
1778: * @see #setDefaultUncaughtExceptionHandler
1779: * @see #setUncaughtExceptionHandler
1780: * @see ThreadGroup#uncaughtException
1781: * @since 1.5
1782: */
1783: public interface UncaughtExceptionHandler {
1784: /**
1785: * Method invoked when the given thread terminates due to the
1786: * given uncaught exception.
1787: * <p>Any exception thrown by this method will be ignored by the
1788: * Java Virtual Machine.
1789: * @param t the thread
1790: * @param e the exception
1791: */
1792: void uncaughtException(Thread t, Throwable e);
1793: }
1794:
1795: // null unless explicitly set
1796: private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
1797:
1798: // null unless explicitly set
1799: private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
1800:
1801: /**
1802: * Set the default handler invoked when a thread abruptly terminates
1803: * due to an uncaught exception, and no other handler has been defined
1804: * for that thread.
1805: *
1806: * <p>Uncaught exception handling is controlled first by the thread, then
1807: * by the thread's {@link ThreadGroup} object and finally by the default
1808: * uncaught exception handler. If the thread does not have an explicit
1809: * uncaught exception handler set, and the thread's thread group
1810: * (including parent thread groups) does not specialize its
1811: * <tt>uncaughtException</tt> method, then the default handler's
1812: * <tt>uncaughtException</tt> method will be invoked.
1813: * <p>By setting the default uncaught exception handler, an application
1814: * can change the way in which uncaught exceptions are handled (such as
1815: * logging to a specific device, or file) for those threads that would
1816: * already accept whatever "default" behavior the system
1817: * provided.
1818: *
1819: * <p>Note that the default uncaught exception handler should not usually
1820: * defer to the thread's <tt>ThreadGroup</tt> object, as that could cause
1821: * infinite recursion.
1822: *
1823: * @param eh the object to use as the default uncaught exception handler.
1824: * If <tt>null</tt> then there is no default handler.
1825: *
1826: * @throws SecurityException if a security manager is present and it
1827: * denies <tt>{@link RuntimePermission}
1828: * ("setDefaultUncaughtExceptionHandler")</tt>
1829: *
1830: * @see #setUncaughtExceptionHandler
1831: * @see #getUncaughtExceptionHandler
1832: * @see ThreadGroup#uncaughtException
1833: * @since 1.5
1834: */
1835: public static void setDefaultUncaughtExceptionHandler(
1836: UncaughtExceptionHandler eh) {
1837: SecurityManager sm = System.getSecurityManager();
1838: if (sm != null) {
1839: sm.checkPermission(new RuntimePermission(
1840: "setDefaultUncaughtExceptionHandler"));
1841: }
1842:
1843: defaultUncaughtExceptionHandler = eh;
1844: }
1845:
1846: /**
1847: * Returns the default handler invoked when a thread abruptly terminates
1848: * due to an uncaught exception. If the returned value is <tt>null</tt>,
1849: * there is no default.
1850: * @since 1.5
1851: * @see #setDefaultUncaughtExceptionHandler
1852: */
1853: public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() {
1854: return defaultUncaughtExceptionHandler;
1855: }
1856:
1857: /**
1858: * Returns the handler invoked when this thread abruptly terminates
1859: * due to an uncaught exception. If this thread has not had an
1860: * uncaught exception handler explicitly set then this thread's
1861: * <tt>ThreadGroup</tt> object is returned, unless this thread
1862: * has terminated, in which case <tt>null</tt> is returned.
1863: * @since 1.5
1864: */
1865: public UncaughtExceptionHandler getUncaughtExceptionHandler() {
1866: return uncaughtExceptionHandler != null ? uncaughtExceptionHandler
1867: : group;
1868: }
1869:
1870: /**
1871: * Set the handler invoked when this thread abruptly terminates
1872: * due to an uncaught exception.
1873: * <p>A thread can take full control of how it responds to uncaught
1874: * exceptions by having its uncaught exception handler explicitly set.
1875: * If no such handler is set then the thread's <tt>ThreadGroup</tt>
1876: * object acts as its handler.
1877: * @param eh the object to use as this thread's uncaught exception
1878: * handler. If <tt>null</tt> then this thread has no explicit handler.
1879: * @throws SecurityException if the current thread is not allowed to
1880: * modify this thread.
1881: * @see #setDefaultUncaughtExceptionHandler
1882: * @see ThreadGroup#uncaughtException
1883: * @since 1.5
1884: */
1885: public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
1886: checkAccess();
1887: uncaughtExceptionHandler = eh;
1888: }
1889:
1890: /**
1891: * Dispatch an uncaught exception to the handler. This method is
1892: * intended to be called only by the JVM.
1893: */
1894: private void dispatchUncaughtException(Throwable e) {
1895: getUncaughtExceptionHandler().uncaughtException(this , e);
1896: }
1897:
1898: /* Some private helper methods */
1899: private native void setPriority0(int newPriority);
1900:
1901: private native void stop0(Object o);
1902:
1903: private native void suspend0();
1904:
1905: private native void resume0();
1906:
1907: private native void interrupt0();
1908: }
|