1 /* Thread -- an independent thread of executable code
2 Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
3 Free Software Foundation
5 This file is part of GNU Classpath.
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING. If not, write to the
19 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library. Thus, the terms and
24 conditions of the GNU General Public License cover the whole
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module. An independent module is a module which is not derived from
34 or based on this library. If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so. If you do not wish to do so, delete this
37 exception statement from your version. */
41 import gnu.classpath.VMStackWalker;
42 import gnu.gcj.RawData;
43 import gnu.gcj.RawDataManaged;
44 import gnu.java.util.WeakIdentityHashMap;
46 import java.lang.management.ManagementFactory;
47 import java.lang.management.ThreadInfo;
48 import java.lang.management.ThreadMXBean;
50 import java.util.HashMap;
53 /* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3
54 * "The Java Language Specification", ISBN 0-201-63451-1
55 * plus online API docs for JDK 1.2 beta from http://www.javasoft.com.
56 * Status: Believed complete to version 1.4, with caveats. We do not
57 * implement the deprecated (and dangerous) stop, suspend, and resume
58 * methods. Security implementation is not complete.
62 * Thread represents a single thread of execution in the VM. When an
63 * application VM starts up, it creates a non-daemon Thread which calls the
64 * main() method of a particular class. There may be other Threads running,
65 * such as the garbage collection thread.
67 * <p>Threads have names to identify them. These names are not necessarily
68 * unique. Every Thread has a priority, as well, which tells the VM which
69 * Threads should get more running time. New threads inherit the priority
70 * and daemon status of the parent thread, by default.
72 * <p>There are two methods of creating a Thread: you may subclass Thread and
73 * implement the <code>run()</code> method, at which point you may start the
74 * Thread by calling its <code>start()</code> method, or you may implement
75 * <code>Runnable</code> in the class you want to use and then call new
76 * <code>Thread(your_obj).start()</code>.
78 * <p>The virtual machine runs until all non-daemon threads have died (either
79 * by returning from the run() method as invoked by start(), or by throwing
80 * an uncaught exception); or until <code>System.exit</code> is called with
81 * adequate permissions.
83 * <p>It is unclear at what point a Thread should be added to a ThreadGroup,
84 * and at what point it should be removed. Should it be inserted when it
85 * starts, or when it is created? Should it be removed when it is suspended
86 * or interrupted? The only thing that is clear is that the Thread should be
87 * removed when it is stopped.
91 * @author Eric Blake (ebb9@email.byu.edu)
92 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
94 * @see Runtime#exit(int)
99 * @status updated to 1.4
101 public class Thread implements Runnable
103 /** The minimum priority for a Thread. */
104 public static final int MIN_PRIORITY = 1;
106 /** The priority a Thread gets by default. */
107 public static final int NORM_PRIORITY = 5;
109 /** The maximum priority for a Thread. */
110 public static final int MAX_PRIORITY = 10;
113 * The group this thread belongs to. This is set to null by
114 * ThreadGroup.removeThread when the thread dies.
118 /** The object to run(), null if this is the target. */
119 private Runnable runnable;
121 /** The thread name, non-null. */
124 /** Whether the thread is a daemon. */
125 private boolean daemon;
127 /** The thread priority, 1 to 10. */
128 private int priority;
130 boolean interrupt_flag;
132 /** A thread is either alive, dead, or being sent a signal; if it is
133 being sent a signal, it is also alive. Thus, if you want to
134 know if a thread is alive, it is sufficient to test
135 alive_status != THREAD_DEAD. */
136 private static final byte THREAD_DEAD = 0;
137 private static final byte THREAD_ALIVE = 1;
138 private static final byte THREAD_SIGNALED = 2;
140 private boolean startable_flag;
142 /** The context classloader for this Thread. */
143 private ClassLoader contextClassLoader;
145 /** This thread's ID. */
146 private final long threadId;
148 /** The next thread ID to use. */
149 private static long nextThreadId;
151 /** Used to generate the next thread ID to use. */
152 private static long totalThreadsCreated;
154 /** The default exception handler. */
155 private static UncaughtExceptionHandler defaultHandler;
157 /** Thread local storage. Package accessible for use by
158 * InheritableThreadLocal.
160 WeakIdentityHashMap locals;
162 /** The uncaught exception handler. */
163 UncaughtExceptionHandler exceptionHandler;
165 /** This object is recorded while the thread is blocked to permit
166 * monitoring and diagnostic tools to identify the reasons that
167 * threads are blocked.
169 private Object parkBlocker;
171 /** Used by Unsafe.park and Unsafe.unpark. Se Unsafe for a full
173 static final byte THREAD_PARK_RUNNING = 0;
174 static final byte THREAD_PARK_PERMIT = 1;
175 static final byte THREAD_PARK_PARKED = 2;
176 static final byte THREAD_PARK_DEAD = 3;
178 /** The access control state for this thread. Package accessible
179 * for use by java.security.VMAccessControlState's native method.
181 Object accessControlState = null;
183 // This describes the top-most interpreter frame for this thread.
184 RawData interp_frame;
186 // This describes the top most frame in the composite (interp + JNI) stack
192 // Our native data - points to an instance of struct natThread.
196 * Allocates a new <code>Thread</code> object. This constructor has
197 * the same effect as <code>Thread(null, null,</code>
198 * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
199 * a newly generated name. Automatically generated names are of the
200 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
202 * Threads created this way must have overridden their
203 * <code>run()</code> method to actually do anything. An example
204 * illustrating this method being used follows:
205 * <p><blockquote><pre>
206 * import java.lang.*;
208 * class plain01 implements Runnable {
213 * plain01(String s) {
216 * public void run() {
218 * System.out.println("A new thread created");
220 * System.out.println("A new thread with name " + name +
224 * class threadtest01 {
225 * public static void main(String args[] ) {
228 * <b>Thread t1 = new Thread();</b>
230 * System.out.println("new Thread() succeed");
232 * System.out.println("new Thread() failed");
237 * </pre></blockquote>
239 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
240 * java.lang.Runnable, java.lang.String)
244 this(null, null, gen_name());
248 * Allocates a new <code>Thread</code> object. This constructor has
249 * the same effect as <code>Thread(null, target,</code>
250 * <i>gname</i><code>)</code>, where <i>gname</i> is
251 * a newly generated name. Automatically generated names are of the
252 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
254 * @param target the object whose <code>run</code> method is called.
255 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
256 * java.lang.Runnable, java.lang.String)
258 public Thread(Runnable target)
260 this(null, target, gen_name());
264 * Allocates a new <code>Thread</code> object. This constructor has
265 * the same effect as <code>Thread(null, null, name)</code>.
267 * @param name the name of the new thread.
268 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
269 * java.lang.Runnable, java.lang.String)
271 public Thread(String name)
273 this(null, null, name);
277 * Allocates a new <code>Thread</code> object. This constructor has
278 * the same effect as <code>Thread(group, target,</code>
279 * <i>gname</i><code>)</code>, where <i>gname</i> is
280 * a newly generated name. Automatically generated names are of the
281 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
283 * @param group the group to put the Thread into
284 * @param target the Runnable object to execute
285 * @throws SecurityException if this thread cannot access <code>group</code>
286 * @throws IllegalThreadStateException if group is destroyed
287 * @see #Thread(ThreadGroup, Runnable, String)
289 public Thread(ThreadGroup group, Runnable target)
291 this(group, target, gen_name());
295 * Allocates a new <code>Thread</code> object. This constructor has
296 * the same effect as <code>Thread(group, null, name)</code>
298 * @param group the group to put the Thread into
299 * @param name the name for the Thread
300 * @throws NullPointerException if name is null
301 * @throws SecurityException if this thread cannot access <code>group</code>
302 * @throws IllegalThreadStateException if group is destroyed
303 * @see #Thread(ThreadGroup, Runnable, String)
305 public Thread(ThreadGroup group, String name)
307 this(group, null, name);
311 * Allocates a new <code>Thread</code> object. This constructor has
312 * the same effect as <code>Thread(null, target, name)</code>.
314 * @param target the Runnable object to execute
315 * @param name the name for the Thread
316 * @throws NullPointerException if name is null
317 * @see #Thread(ThreadGroup, Runnable, String)
319 public Thread(Runnable target, String name)
321 this(null, target, name);
325 * Allocate a new Thread object, with the specified ThreadGroup and name, and
326 * using the specified Runnable object's <code>run()</code> method to
327 * execute. If the Runnable object is null, <code>this</code> (which is
328 * a Runnable) is used instead.
330 * <p>If the ThreadGroup is null, the security manager is checked. If a
331 * manager exists and returns a non-null object for
332 * <code>getThreadGroup</code>, that group is used; otherwise the group
333 * of the creating thread is used. Note that the security manager calls
334 * <code>checkAccess</code> if the ThreadGroup is not null.
336 * <p>The new Thread will inherit its creator's priority and daemon status.
337 * These can be changed with <code>setPriority</code> and
338 * <code>setDaemon</code>.
340 * @param group the group to put the Thread into
341 * @param target the Runnable object to execute
342 * @param name the name for the Thread
343 * @throws NullPointerException if name is null
344 * @throws SecurityException if this thread cannot access <code>group</code>
345 * @throws IllegalThreadStateException if group is destroyed
346 * @see Runnable#run()
348 * @see #setDaemon(boolean)
349 * @see #setPriority(int)
350 * @see SecurityManager#checkAccess(ThreadGroup)
351 * @see ThreadGroup#checkAccess()
353 public Thread(ThreadGroup group, Runnable target, String name)
355 this(currentThread(), group, target, name);
359 * Allocate a new Thread object, as if by
360 * <code>Thread(group, null, name)</code>, and give it the specified stack
361 * size, in bytes. The stack size is <b>highly platform independent</b>,
362 * and the virtual machine is free to round up or down, or ignore it
363 * completely. A higher value might let you go longer before a
364 * <code>StackOverflowError</code>, while a lower value might let you go
365 * longer before an <code>OutOfMemoryError</code>. Or, it may do absolutely
366 * nothing! So be careful, and expect to need to tune this value if your
367 * virtual machine even supports it.
369 * @param group the group to put the Thread into
370 * @param target the Runnable object to execute
371 * @param name the name for the Thread
372 * @param size the stack size, in bytes; 0 to be ignored
373 * @throws NullPointerException if name is null
374 * @throws SecurityException if this thread cannot access <code>group</code>
375 * @throws IllegalThreadStateException if group is destroyed
378 public Thread(ThreadGroup group, Runnable target, String name, long size)
380 // Just ignore stackSize for now.
381 this(currentThread(), group, target, name);
384 private Thread (Thread current, ThreadGroup g, Runnable r, String n)
386 // Make sure the current thread may create a new thread.
389 // The Class Libraries book says ``threadName cannot be null''. I
390 // take this to mean NullPointerException.
392 throw new NullPointerException ();
396 // If CURRENT is null, then we are bootstrapping the first thread.
397 // Use ThreadGroup.root, the main threadgroup.
399 group = ThreadGroup.root;
401 group = current.getThreadGroup();
407 interrupt_flag = false;
408 startable_flag = true;
410 synchronized (Thread.class)
412 this.threadId = nextThreadId++;
419 daemon = current.isDaemon();
420 int gmax = group.getMaxPriority();
421 int pri = current.getPriority();
422 priority = (gmax < pri ? gmax : pri);
423 contextClassLoader = current.contextClassLoader;
424 InheritableThreadLocal.newChildThread(this);
429 priority = NORM_PRIORITY;
433 group.addThread(this);
436 initialize_native ();
440 * Get the number of active threads in the current Thread's ThreadGroup.
441 * This implementation calls
442 * <code>currentThread().getThreadGroup().activeCount()</code>.
444 * @return the number of active threads in the current ThreadGroup
445 * @see ThreadGroup#activeCount()
447 public static int activeCount()
449 return currentThread().group.activeCount();
453 * Check whether the current Thread is allowed to modify this Thread. This
454 * passes the check on to <code>SecurityManager.checkAccess(this)</code>.
456 * @throws SecurityException if the current Thread cannot modify this Thread
457 * @see SecurityManager#checkAccess(Thread)
459 public final void checkAccess()
461 SecurityManager sm = System.getSecurityManager();
463 sm.checkAccess(this);
467 * Count the number of stack frames in this Thread. The Thread in question
468 * must be suspended when this occurs.
470 * @return the number of stack frames in this Thread
471 * @throws IllegalThreadStateException if this Thread is not suspended
472 * @deprecated pointless, since suspend is deprecated
474 public native int countStackFrames();
477 * Get the currently executing Thread. In the situation that the
478 * currently running thread was created by native code and doesn't
479 * have an associated Thread object yet, a new Thread object is
480 * constructed and associated with the native thread.
482 * @return the currently executing Thread
484 public static native Thread currentThread();
487 * Originally intended to destroy this thread, this method was never
488 * implemented by Sun, and is hence a no-op.
490 * @deprecated This method was originally intended to simply destroy
491 * the thread without performing any form of cleanup operation.
492 * However, it was never implemented. It is now deprecated
493 * for the same reason as <code>suspend()</code>,
494 * <code>stop()</code> and <code>resume()</code>; namely,
495 * it is prone to deadlocks. If a thread is destroyed while
496 * it still maintains a lock on a resource, then this resource
497 * will remain locked and any attempts by other threads to
498 * access the resource will result in a deadlock. Thus, even
499 * an implemented version of this method would be still be
500 * deprecated, due to its unsafe nature.
501 * @throws NoSuchMethodError as this method was never implemented.
503 public void destroy()
505 throw new NoSuchMethodError();
509 * Print a stack trace of the current thread to stderr using the same
510 * format as Throwable's printStackTrace() method.
512 * @see Throwable#printStackTrace()
514 public static void dumpStack()
516 (new Exception("Stack trace")).printStackTrace();
520 * Copy every active thread in the current Thread's ThreadGroup into the
521 * array. Extra threads are silently ignored. This implementation calls
522 * <code>getThreadGroup().enumerate(array)</code>, which may have a
523 * security check, <code>checkAccess(group)</code>.
525 * @param array the array to place the Threads into
526 * @return the number of Threads placed into the array
527 * @throws NullPointerException if array is null
528 * @throws SecurityException if you cannot access the ThreadGroup
529 * @see ThreadGroup#enumerate(Thread[])
530 * @see #activeCount()
531 * @see SecurityManager#checkAccess(ThreadGroup)
533 public static int enumerate(Thread[] array)
535 return currentThread().group.enumerate(array);
539 * Get this Thread's name.
541 * @return this Thread's name
543 public final String getName()
549 * Get this Thread's priority.
551 * @return the Thread's priority
553 public final int getPriority()
559 * Get the ThreadGroup this Thread belongs to. If the thread has died, this
562 * @return this Thread's ThreadGroup
564 public final ThreadGroup getThreadGroup()
570 * Checks whether the current thread holds the monitor on a given object.
571 * This allows you to do <code>assert Thread.holdsLock(obj)</code>.
573 * @param obj the object to test lock ownership on.
574 * @return true if the current thread is currently synchronized on obj
575 * @throws NullPointerException if obj is null
578 public static native boolean holdsLock(Object obj);
581 * Interrupt this Thread. First, there is a security check,
582 * <code>checkAccess</code>. Then, depending on the current state of the
583 * thread, various actions take place:
585 * <p>If the thread is waiting because of {@link #wait()},
586 * {@link #sleep(long)}, or {@link #join()}, its <i>interrupt status</i>
587 * will be cleared, and an InterruptedException will be thrown. Notice that
588 * this case is only possible if an external thread called interrupt().
590 * <p>If the thread is blocked in an interruptible I/O operation, in
591 * {@link java.nio.channels.InterruptibleChannel}, the <i>interrupt
592 * status</i> will be set, and ClosedByInterruptException will be thrown.
594 * <p>If the thread is blocked on a {@link java.nio.channels.Selector}, the
595 * <i>interrupt status</i> will be set, and the selection will return, with
596 * a possible non-zero value, as though by the wakeup() method.
598 * <p>Otherwise, the interrupt status will be set.
600 * @throws SecurityException if you cannot modify this Thread
602 public native void interrupt();
605 * Determine whether the current Thread has been interrupted, and clear
606 * the <i>interrupted status</i> in the process.
608 * @return whether the current Thread has been interrupted
609 * @see #isInterrupted()
611 public static boolean interrupted()
613 return currentThread().isInterrupted(true);
617 * Determine whether the given Thread has been interrupted, but leave
618 * the <i>interrupted status</i> alone in the process.
620 * @return whether the Thread has been interrupted
621 * @see #interrupted()
623 public boolean isInterrupted()
625 return interrupt_flag;
629 * Determine whether this Thread is alive. A thread which is alive has
630 * started and not yet died.
632 * @return whether this Thread is alive
634 public final native boolean isAlive();
637 * Tell whether this is a daemon Thread or not.
639 * @return whether this is a daemon Thread or not
640 * @see #setDaemon(boolean)
642 public final boolean isDaemon()
648 * Wait forever for the Thread in question to die.
650 * @throws InterruptedException if the Thread is interrupted; it's
651 * <i>interrupted status</i> will be cleared
653 public final void join() throws InterruptedException
659 * Wait the specified amount of time for the Thread in question to die.
661 * @param ms the number of milliseconds to wait, or 0 for forever
662 * @throws InterruptedException if the Thread is interrupted; it's
663 * <i>interrupted status</i> will be cleared
665 public final void join(long ms) throws InterruptedException
671 * Wait the specified amount of time for the Thread in question to die.
673 * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
674 * not offer that fine a grain of timing resolution. Besides, there is
675 * no guarantee that this thread can start up immediately when time expires,
676 * because some other thread may be active. So don't expect real-time
679 * @param ms the number of milliseconds to wait, or 0 for forever
680 * @param ns the number of extra nanoseconds to sleep (0-999999)
681 * @throws InterruptedException if the Thread is interrupted; it's
682 * <i>interrupted status</i> will be cleared
683 * @throws IllegalArgumentException if ns is invalid
684 * @XXX A ThreadListener would be nice, to make this efficient.
686 public final native void join(long ms, int ns)
687 throws InterruptedException;
690 * Resume this Thread. If the thread is not suspended, this method does
691 * nothing. To mirror suspend(), there may be a security check:
692 * <code>checkAccess</code>.
694 * @throws SecurityException if you cannot resume the Thread
695 * @see #checkAccess()
697 * @deprecated pointless, since suspend is deprecated
699 public final native void resume();
701 private final native void finish_();
704 * Determine whether the given Thread has been interrupted, but leave
705 * the <i>interrupted status</i> alone in the process.
707 * @return whether the current Thread has been interrupted
708 * @see #interrupted()
710 private boolean isInterrupted(boolean clear_flag)
712 boolean r = interrupt_flag;
715 // Only clear the flag if we saw it as set. Otherwise this could
716 // potentially cause us to miss an interrupt in a race condition,
717 // because this method is not synchronized.
718 interrupt_flag = false;
724 * The method of Thread that will be run if there is no Runnable object
725 * associated with the Thread. Thread's implementation does nothing at all.
728 * @see #Thread(ThreadGroup, Runnable, String)
732 if (runnable != null)
737 * Set the daemon status of this Thread. If this is a daemon Thread, then
738 * the VM may exit even if it is still running. This may only be called
739 * before the Thread starts running. There may be a security check,
740 * <code>checkAccess</code>.
742 * @param daemon whether this should be a daemon thread or not
743 * @throws SecurityException if you cannot modify this Thread
744 * @throws IllegalThreadStateException if the Thread is active
746 * @see #checkAccess()
748 public final void setDaemon(boolean daemon)
751 throw new IllegalThreadStateException();
753 this.daemon = daemon;
757 * Returns the context classloader of this Thread. The context
758 * classloader can be used by code that want to load classes depending
759 * on the current thread. Normally classes are loaded depending on
760 * the classloader of the current class. There may be a security check
761 * for <code>RuntimePermission("getClassLoader")</code> if the caller's
762 * class loader is not null or an ancestor of this thread's context class
765 * @return the context class loader
766 * @throws SecurityException when permission is denied
767 * @see #setContextClassLoader(ClassLoader)
770 public synchronized ClassLoader getContextClassLoader()
772 if (contextClassLoader == null)
773 contextClassLoader = ClassLoader.getSystemClassLoader();
775 // Check if we may get the classloader
776 SecurityManager sm = System.getSecurityManager();
777 if (contextClassLoader != null && sm != null)
779 // Get the calling classloader
780 ClassLoader cl = VMStackWalker.getCallingClassLoader();
781 if (cl != null && !cl.isAncestorOf(contextClassLoader))
782 sm.checkPermission(new RuntimePermission("getClassLoader"));
784 return contextClassLoader;
788 * Sets the context classloader for this Thread. When not explicitly set,
789 * the context classloader for a thread is the same as the context
790 * classloader of the thread that created this thread. The first thread has
791 * as context classloader the system classloader. There may be a security
792 * check for <code>RuntimePermission("setContextClassLoader")</code>.
794 * @param classloader the new context class loader
795 * @throws SecurityException when permission is denied
796 * @see #getContextClassLoader()
799 public synchronized void setContextClassLoader(ClassLoader classloader)
801 SecurityManager sm = System.getSecurityManager();
803 sm.checkPermission(new RuntimePermission("setContextClassLoader"));
804 this.contextClassLoader = classloader;
808 * Set this Thread's name. There may be a security check,
809 * <code>checkAccess</code>.
811 * @param name the new name for this Thread
812 * @throws NullPointerException if name is null
813 * @throws SecurityException if you cannot modify this Thread
815 public final void setName(String name)
818 // The Class Libraries book says ``threadName cannot be null''. I
819 // take this to mean NullPointerException.
821 throw new NullPointerException();
826 * Yield to another thread. The Thread will not lose any locks it holds
827 * during this time. There are no guarantees which thread will be
828 * next to run, and it could even be this one, but most VMs will choose
829 * the highest priority thread that has been waiting longest.
831 public static native void yield();
834 * Suspend the current Thread's execution for the specified amount of
835 * time. The Thread will not lose any locks it has during this time. There
836 * are no guarantees which thread will be next to run, but most VMs will
837 * choose the highest priority thread that has been waiting longest.
839 * @param ms the number of milliseconds to sleep, or 0 for forever
840 * @throws InterruptedException if the Thread is (or was) interrupted;
841 * it's <i>interrupted status</i> will be cleared
842 * @throws IllegalArgumentException if ms is negative
847 public static void sleep(long ms) throws InterruptedException
853 * Suspend the current Thread's execution for the specified amount of
854 * time. The Thread will not lose any locks it has during this time. There
855 * are no guarantees which thread will be next to run, but most VMs will
856 * choose the highest priority thread that has been waiting longest.
858 * Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs
859 * do not offer that fine a grain of timing resolution. When ms is
860 * zero and ns is non-zero the Thread will sleep for at least one
861 * milli second. There is no guarantee that this thread can start up
862 * immediately when time expires, because some other thread may be
863 * active. So don't expect real-time performance.
865 * @param ms the number of milliseconds to sleep, or 0 for forever
866 * @param ns the number of extra nanoseconds to sleep (0-999999)
867 * @throws InterruptedException if the Thread is (or was) interrupted;
868 * it's <i>interrupted status</i> will be cleared
869 * @throws IllegalArgumentException if ms or ns is negative
870 * or ns is larger than 999999.
873 * @see #wait(long, int)
875 public static native void sleep(long timeout, int nanos)
876 throws InterruptedException;
879 * Start this Thread, calling the run() method of the Runnable this Thread
880 * was created with, or else the run() method of the Thread itself. This
881 * is the only way to start a new thread; calling run by yourself will just
882 * stay in the same thread. The virtual machine will remove the thread from
883 * its thread group when the run() method completes.
885 * @throws IllegalThreadStateException if the thread has already started
888 public native void start();
891 * Cause this Thread to stop abnormally because of the throw of a ThreadDeath
892 * error. If you stop a Thread that has not yet started, it will stop
893 * immediately when it is actually started.
895 * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
896 * leave data in bad states. Hence, there is a security check:
897 * <code>checkAccess(this)</code>, plus another one if the current thread
898 * is not this: <code>RuntimePermission("stopThread")</code>. If you must
899 * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
900 * ThreadDeath is the only exception which does not print a stack trace when
903 * @throws SecurityException if you cannot stop the Thread
905 * @see #checkAccess()
908 * @see ThreadGroup#uncaughtException(Thread, Throwable)
909 * @see SecurityManager#checkAccess(Thread)
910 * @see SecurityManager#checkPermission(Permission)
911 * @deprecated unsafe operation, try not to use
913 public final void stop()
915 // Argument doesn't matter, because this is no longer
921 * Cause this Thread to stop abnormally and throw the specified exception.
922 * If you stop a Thread that has not yet started, the stop is ignored
923 * (contrary to what the JDK documentation says).
924 * <b>WARNING</b>This bypasses Java security, and can throw a checked
925 * exception which the call stack is unprepared to handle. Do not abuse
928 * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
929 * leave data in bad states. Hence, there is a security check:
930 * <code>checkAccess(this)</code>, plus another one if the current thread
931 * is not this: <code>RuntimePermission("stopThread")</code>. If you must
932 * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
933 * ThreadDeath is the only exception which does not print a stack trace when
936 * @param t the Throwable to throw when the Thread dies
937 * @throws SecurityException if you cannot stop the Thread
938 * @throws NullPointerException in the calling thread, if t is null
940 * @see #checkAccess()
943 * @see ThreadGroup#uncaughtException(Thread, Throwable)
944 * @see SecurityManager#checkAccess(Thread)
945 * @see SecurityManager#checkPermission(Permission)
946 * @deprecated unsafe operation, try not to use
948 public final native void stop(Throwable t);
951 * Suspend this Thread. It will not come back, ever, unless it is resumed.
953 * <p>This is inherently unsafe, as the suspended thread still holds locks,
954 * and can potentially deadlock your program. Hence, there is a security
955 * check: <code>checkAccess</code>.
957 * @throws SecurityException if you cannot suspend the Thread
958 * @see #checkAccess()
960 * @deprecated unsafe operation, try not to use
962 public final native void suspend();
965 * Set this Thread's priority. There may be a security check,
966 * <code>checkAccess</code>, then the priority is set to the smaller of
967 * priority and the ThreadGroup maximum priority.
969 * @param priority the new priority for this Thread
970 * @throws IllegalArgumentException if priority exceeds MIN_PRIORITY or
972 * @throws SecurityException if you cannot modify this Thread
973 * @see #getPriority()
974 * @see #checkAccess()
975 * @see ThreadGroup#getMaxPriority()
979 public final native void setPriority(int newPriority);
982 * Returns a string representation of this thread, including the
983 * thread's name, priority, and thread group.
985 * @return a human-readable String representing this Thread
987 public String toString()
989 return ("Thread[" + name + "," + priority + ","
990 + (group == null ? "" : group.getName()) + "]");
993 private final native void initialize_native();
995 private final native static String gen_name();
998 * Returns the map used by ThreadLocal to store the thread local values.
1000 static Map getThreadLocals()
1002 Thread thread = currentThread();
1003 Map locals = thread.locals;
1006 locals = thread.locals = new WeakIdentityHashMap();
1012 * Assigns the given <code>UncaughtExceptionHandler</code> to this
1013 * thread. This will then be called if the thread terminates due
1014 * to an uncaught exception, pre-empting that of the
1015 * <code>ThreadGroup</code>.
1017 * @param h the handler to use for this thread.
1018 * @throws SecurityException if the current thread can't modify this thread.
1021 public void setUncaughtExceptionHandler(UncaughtExceptionHandler h)
1023 SecurityManager sm = SecurityManager.current; // Be thread-safe.
1025 sm.checkAccess(this);
1026 exceptionHandler = h;
1031 * Returns the handler used when this thread terminates due to an
1032 * uncaught exception. The handler used is determined by the following:
1035 * <li>If this thread has its own handler, this is returned.</li>
1036 * <li>If not, then the handler of the thread's <code>ThreadGroup</code>
1037 * object is returned.</li>
1038 * <li>If both are unavailable, then <code>null</code> is returned
1039 * (which can only happen when the thread was terminated since
1040 * then it won't have an associated thread group anymore).</li>
1043 * @return the appropriate <code>UncaughtExceptionHandler</code> or
1044 * <code>null</code> if one can't be obtained.
1047 public UncaughtExceptionHandler getUncaughtExceptionHandler()
1049 // FIXME: if thread is dead, should return null...
1050 return exceptionHandler != null ? exceptionHandler : group;
1055 * Sets the default uncaught exception handler used when one isn't
1056 * provided by the thread or its associated <code>ThreadGroup</code>.
1057 * This exception handler is used when the thread itself does not
1058 * have an exception handler, and the thread's <code>ThreadGroup</code>
1059 * does not override this default mechanism with its own. As the group
1060 * calls this handler by default, this exception handler should not defer
1061 * to that of the group, as it may lead to infinite recursion.
1064 * Uncaught exception handlers are used when a thread terminates due to
1065 * an uncaught exception. Replacing this handler allows default code to
1066 * be put in place for all threads in order to handle this eventuality.
1069 * @param h the new default uncaught exception handler to use.
1070 * @throws SecurityException if a security manager is present and
1071 * disallows the runtime permission
1072 * "setDefaultUncaughtExceptionHandler".
1076 setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler h)
1078 SecurityManager sm = SecurityManager.current; // Be thread-safe.
1080 sm.checkPermission(new RuntimePermission("setDefaultUncaughtExceptionHandler"));
1085 * Returns the handler used by default when a thread terminates
1086 * unexpectedly due to an exception, or <code>null</code> if one doesn't
1089 * @return the default uncaught exception handler.
1092 public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
1094 return defaultHandler;
1098 * Returns the unique identifier for this thread. This ID is generated
1099 * on thread creation, and may be re-used on its death.
1101 * @return a positive long number representing the thread's ID.
1111 * This interface is used to handle uncaught exceptions
1112 * which cause a <code>Thread</code> to terminate. When
1113 * a thread, t, is about to terminate due to an uncaught
1114 * exception, the virtual machine looks for a class which
1115 * implements this interface, in order to supply it with
1116 * the dying thread and its uncaught exception.
1119 * The virtual machine makes two attempts to find an
1120 * appropriate handler for the uncaught exception, in
1121 * the following order:
1125 * <code>t.getUncaughtExceptionHandler()</code> --
1126 * the dying thread is queried first for a handler
1127 * specific to that thread.
1130 * <code>t.getThreadGroup()</code> --
1131 * the thread group of the dying thread is used to
1132 * handle the exception. If the thread group has
1133 * no special requirements for handling the exception,
1134 * it may simply forward it on to
1135 * <code>Thread.getDefaultUncaughtExceptionHandler()</code>,
1136 * the default handler, which is used as a last resort.
1140 * The first handler found is the one used to handle
1141 * the uncaught exception.
1144 * @author Tom Tromey <tromey@redhat.com>
1145 * @author Andrew John Hughes <gnu_andrew@member.fsf.org>
1147 * @see Thread#getUncaughtExceptionHandler()
1148 * @see Thread#setUncaughtExceptionHandler(UncaughtExceptionHandler)
1149 * @see Thread#getDefaultUncaughtExceptionHandler()
1151 * Thread#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)
1153 public interface UncaughtExceptionHandler
1156 * Invoked by the virtual machine with the dying thread
1157 * and the uncaught exception. Any exceptions thrown
1158 * by this method are simply ignored by the virtual
1161 * @param thr the dying thread.
1162 * @param exc the uncaught exception.
1164 void uncaughtException(Thread thr, Throwable exc);
1169 * Represents the current state of a thread, according to the VM rather
1170 * than the operating system. It can be one of the following:
1173 * <li>NEW -- The thread has just been created but is not yet running.</li>
1174 * <li>RUNNABLE -- The thread is currently running or can be scheduled
1176 * <li>BLOCKED -- The thread is blocked waiting on an I/O operation
1177 * or to obtain a lock.</li>
1178 * <li>WAITING -- The thread is waiting indefinitely for another thread
1179 * to do something.</li>
1180 * <li>TIMED_WAITING -- The thread is waiting for a specific amount of time
1181 * for another thread to do something.</li>
1182 * <li>TERMINATED -- The thread has exited.</li>
1189 BLOCKED, NEW, RUNNABLE, TERMINATED, TIMED_WAITING, WAITING;
1194 * Returns the current state of the thread. This
1195 * is designed for monitoring thread behaviour, rather
1196 * than for synchronization control.
1198 * @return the current thread state.
1200 public native State getState();
1204 * Returns a map of threads to stack traces for each
1205 * live thread. The keys of the map are {@link Thread}
1206 * objects, which map to arrays of {@link StackTraceElement}s.
1207 * The results obtained from Calling this method are
1208 * equivalent to calling {@link getStackTrace()} on each
1209 * thread in succession. Threads may be executing while
1210 * this takes place, and the results represent a snapshot
1211 * of the thread at the time its {@link getStackTrace()}
1215 * The stack trace information contains the methods called
1216 * by the thread, with the most recent method forming the
1217 * first element in the array. The array will be empty
1218 * if the virtual machine can not obtain information on the
1222 * To execute this method, the current security manager
1223 * (if one exists) must allow both the
1224 * <code>"getStackTrace"</code> and
1225 * <code>"modifyThreadGroup"</code> {@link RuntimePermission}s.
1228 * @return a map of threads to arrays of {@link StackTraceElement}s.
1229 * @throws SecurityException if a security manager exists, and
1230 * prevents either or both the runtime
1231 * permissions specified above.
1233 * @see #getStackTrace()
1235 public static Map<Thread, StackTraceElement[]> getAllStackTraces()
1237 ThreadGroup group = currentThread().group;
1238 while (group.getParent() != null)
1239 group = group.getParent();
1240 int arraySize = group.activeCount();
1241 Thread[] threadList = new Thread[arraySize];
1242 int filled = group.enumerate(threadList);
1243 while (filled == arraySize)
1246 threadList = new Thread[arraySize];
1247 filled = group.enumerate(threadList);
1249 Map traces = new HashMap();
1250 for (int a = 0; a < filled; ++a)
1251 traces.put(threadList[a],
1252 threadList[a].getStackTrace());
1258 * Returns an array of {@link StackTraceElement}s
1259 * representing the current stack trace of this thread.
1260 * The first element of the array is the most recent
1261 * method called, and represents the top of the stack.
1262 * The elements continue in this order, with the last
1263 * element representing the bottom of the stack.
1266 * A zero element array is returned for threads which
1267 * have not yet started (and thus have not yet executed
1268 * any methods) or for those which have terminated.
1269 * Where the virtual machine can not obtain a trace for
1270 * the thread, an empty array is also returned. The
1271 * virtual machine may also omit some methods from the
1272 * trace in non-zero arrays.
1275 * To execute this method, the current security manager
1276 * (if one exists) must allow both the
1277 * <code>"getStackTrace"</code> and
1278 * <code>"modifyThreadGroup"</code> {@link RuntimePermission}s.
1281 * @return a stack trace for this thread.
1282 * @throws SecurityException if a security manager exists, and
1283 * prevents the use of the
1284 * <code>"getStackTrace"</code>
1287 * @see #getAllStackTraces()
1289 public StackTraceElement[] getStackTrace()
1291 SecurityManager sm = SecurityManager.current; // Be thread-safe.
1293 sm.checkPermission(new RuntimePermission("getStackTrace"));
1294 ThreadMXBean bean = ManagementFactory.getThreadMXBean();
1295 ThreadInfo info = bean.getThreadInfo(getId(), Integer.MAX_VALUE);
1296 return info.getStackTrace();