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. */
42 import gnu.gcj.RawData;
43 import gnu.gcj.RawDataManaged;
44 import gnu.java.util.WeakIdentityHashMap;
47 /* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3
48 * "The Java Language Specification", ISBN 0-201-63451-1
49 * plus online API docs for JDK 1.2 beta from http://www.javasoft.com.
50 * Status: Believed complete to version 1.4, with caveats. We do not
51 * implement the deprecated (and dangerous) stop, suspend, and resume
52 * methods. Security implementation is not complete.
56 * Thread represents a single thread of execution in the VM. When an
57 * application VM starts up, it creates a non-daemon Thread which calls the
58 * main() method of a particular class. There may be other Threads running,
59 * such as the garbage collection thread.
61 * <p>Threads have names to identify them. These names are not necessarily
62 * unique. Every Thread has a priority, as well, which tells the VM which
63 * Threads should get more running time. New threads inherit the priority
64 * and daemon status of the parent thread, by default.
66 * <p>There are two methods of creating a Thread: you may subclass Thread and
67 * implement the <code>run()</code> method, at which point you may start the
68 * Thread by calling its <code>start()</code> method, or you may implement
69 * <code>Runnable</code> in the class you want to use and then call new
70 * <code>Thread(your_obj).start()</code>.
72 * <p>The virtual machine runs until all non-daemon threads have died (either
73 * by returning from the run() method as invoked by start(), or by throwing
74 * an uncaught exception); or until <code>System.exit</code> is called with
75 * adequate permissions.
77 * <p>It is unclear at what point a Thread should be added to a ThreadGroup,
78 * and at what point it should be removed. Should it be inserted when it
79 * starts, or when it is created? Should it be removed when it is suspended
80 * or interrupted? The only thing that is clear is that the Thread should be
81 * removed when it is stopped.
85 * @author Eric Blake (ebb9@email.byu.edu)
87 * @see Runtime#exit(int)
92 * @status updated to 1.4
94 public class Thread implements Runnable
96 /** The minimum priority for a Thread. */
97 public static final int MIN_PRIORITY = 1;
99 /** The priority a Thread gets by default. */
100 public static final int NORM_PRIORITY = 5;
102 /** The maximum priority for a Thread. */
103 public static final int MAX_PRIORITY = 10;
106 * The group this thread belongs to. This is set to null by
107 * ThreadGroup.removeThread when the thread dies.
111 /** The object to run(), null if this is the target. */
112 private Runnable runnable;
114 /** The thread name, non-null. */
117 /** Whether the thread is a daemon. */
118 private boolean daemon;
120 /** The thread priority, 1 to 10. */
121 private int priority;
123 boolean interrupt_flag;
124 private boolean alive_flag;
125 private boolean startable_flag;
127 /** The context classloader for this Thread. */
128 private ClassLoader contextClassLoader;
130 /** This thread's ID. */
131 private final long threadId;
133 /** The next thread ID to use. */
134 private static long nextThreadId;
136 /** The default exception handler. */
137 private static UncaughtExceptionHandler defaultHandler;
139 /** Thread local storage. Package accessible for use by
140 * InheritableThreadLocal.
142 WeakIdentityHashMap locals;
144 /** The uncaught exception handler. */
145 UncaughtExceptionHandler exceptionHandler;
147 // This describes the top-most interpreter frame for this thread.
148 RawData interp_frame;
150 // Our native data - points to an instance of struct natThread.
151 private RawDataManaged data;
154 * Allocates a new <code>Thread</code> object. This constructor has
155 * the same effect as <code>Thread(null, null,</code>
156 * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
157 * a newly generated name. Automatically generated names are of the
158 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
160 * Threads created this way must have overridden their
161 * <code>run()</code> method to actually do anything. An example
162 * illustrating this method being used follows:
163 * <p><blockquote><pre>
164 * import java.lang.*;
166 * class plain01 implements Runnable {
171 * plain01(String s) {
174 * public void run() {
176 * System.out.println("A new thread created");
178 * System.out.println("A new thread with name " + name +
182 * class threadtest01 {
183 * public static void main(String args[] ) {
186 * <b>Thread t1 = new Thread();</b>
188 * System.out.println("new Thread() succeed");
190 * System.out.println("new Thread() failed");
195 * </pre></blockquote>
197 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
198 * java.lang.Runnable, java.lang.String)
202 this(null, null, gen_name());
206 * Allocates a new <code>Thread</code> object. This constructor has
207 * the same effect as <code>Thread(null, target,</code>
208 * <i>gname</i><code>)</code>, where <i>gname</i> is
209 * a newly generated name. Automatically generated names are of the
210 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
212 * @param target the object whose <code>run</code> method is called.
213 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
214 * java.lang.Runnable, java.lang.String)
216 public Thread(Runnable target)
218 this(null, target, gen_name());
222 * Allocates a new <code>Thread</code> object. This constructor has
223 * the same effect as <code>Thread(null, null, name)</code>.
225 * @param name the name of the new thread.
226 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
227 * java.lang.Runnable, java.lang.String)
229 public Thread(String name)
231 this(null, null, name);
235 * Allocates a new <code>Thread</code> object. This constructor has
236 * the same effect as <code>Thread(group, target,</code>
237 * <i>gname</i><code>)</code>, where <i>gname</i> is
238 * a newly generated name. Automatically generated names are of the
239 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
241 * @param group the group to put the Thread into
242 * @param target the Runnable object to execute
243 * @throws SecurityException if this thread cannot access <code>group</code>
244 * @throws IllegalThreadStateException if group is destroyed
245 * @see #Thread(ThreadGroup, Runnable, String)
247 public Thread(ThreadGroup group, Runnable target)
249 this(group, target, gen_name());
253 * Allocates a new <code>Thread</code> object. This constructor has
254 * the same effect as <code>Thread(group, null, name)</code>
256 * @param group the group to put the Thread into
257 * @param name the name for the Thread
258 * @throws NullPointerException if name is null
259 * @throws SecurityException if this thread cannot access <code>group</code>
260 * @throws IllegalThreadStateException if group is destroyed
261 * @see #Thread(ThreadGroup, Runnable, String)
263 public Thread(ThreadGroup group, String name)
265 this(group, null, name);
269 * Allocates a new <code>Thread</code> object. This constructor has
270 * the same effect as <code>Thread(null, target, name)</code>.
272 * @param target the Runnable object to execute
273 * @param name the name for the Thread
274 * @throws NullPointerException if name is null
275 * @see #Thread(ThreadGroup, Runnable, String)
277 public Thread(Runnable target, String name)
279 this(null, target, name);
283 * Allocate a new Thread object, with the specified ThreadGroup and name, and
284 * using the specified Runnable object's <code>run()</code> method to
285 * execute. If the Runnable object is null, <code>this</code> (which is
286 * a Runnable) is used instead.
288 * <p>If the ThreadGroup is null, the security manager is checked. If a
289 * manager exists and returns a non-null object for
290 * <code>getThreadGroup</code>, that group is used; otherwise the group
291 * of the creating thread is used. Note that the security manager calls
292 * <code>checkAccess</code> if the ThreadGroup is not null.
294 * <p>The new Thread will inherit its creator's priority and daemon status.
295 * These can be changed with <code>setPriority</code> and
296 * <code>setDaemon</code>.
298 * @param group the group to put the Thread into
299 * @param target the Runnable object to execute
300 * @param name the name for the Thread
301 * @throws NullPointerException if name is null
302 * @throws SecurityException if this thread cannot access <code>group</code>
303 * @throws IllegalThreadStateException if group is destroyed
304 * @see Runnable#run()
306 * @see #setDaemon(boolean)
307 * @see #setPriority(int)
308 * @see SecurityManager#checkAccess(ThreadGroup)
309 * @see ThreadGroup#checkAccess()
311 public Thread(ThreadGroup group, Runnable target, String name)
313 this(currentThread(), group, target, name);
317 * Allocate a new Thread object, as if by
318 * <code>Thread(group, null, name)</code>, and give it the specified stack
319 * size, in bytes. The stack size is <b>highly platform independent</b>,
320 * and the virtual machine is free to round up or down, or ignore it
321 * completely. A higher value might let you go longer before a
322 * <code>StackOverflowError</code>, while a lower value might let you go
323 * longer before an <code>OutOfMemoryError</code>. Or, it may do absolutely
324 * nothing! So be careful, and expect to need to tune this value if your
325 * virtual machine even supports it.
327 * @param group the group to put the Thread into
328 * @param target the Runnable object to execute
329 * @param name the name for the Thread
330 * @param size the stack size, in bytes; 0 to be ignored
331 * @throws NullPointerException if name is null
332 * @throws SecurityException if this thread cannot access <code>group</code>
333 * @throws IllegalThreadStateException if group is destroyed
336 public Thread(ThreadGroup group, Runnable target, String name, long size)
338 // Just ignore stackSize for now.
339 this(currentThread(), group, target, name);
342 private Thread (Thread current, ThreadGroup g, Runnable r, String n)
344 // Make sure the current thread may create a new thread.
347 // The Class Libraries book says ``threadName cannot be null''. I
348 // take this to mean NullPointerException.
350 throw new NullPointerException ();
354 // If CURRENT is null, then we are bootstrapping the first thread.
355 // Use ThreadGroup.root, the main threadgroup.
357 group = ThreadGroup.root;
359 group = current.getThreadGroup();
365 interrupt_flag = false;
367 startable_flag = true;
369 synchronized (Thread.class)
371 this.threadId = nextThreadId++;
378 daemon = current.isDaemon();
379 int gmax = group.getMaxPriority();
380 int pri = current.getPriority();
381 priority = (gmax < pri ? gmax : pri);
382 contextClassLoader = current.contextClassLoader;
383 InheritableThreadLocal.newChildThread(this);
388 priority = NORM_PRIORITY;
392 group.addThread(this);
395 initialize_native ();
399 * Get the number of active threads in the current Thread's ThreadGroup.
400 * This implementation calls
401 * <code>currentThread().getThreadGroup().activeCount()</code>.
403 * @return the number of active threads in the current ThreadGroup
404 * @see ThreadGroup#activeCount()
406 public static int activeCount()
408 return currentThread().group.activeCount();
412 * Check whether the current Thread is allowed to modify this Thread. This
413 * passes the check on to <code>SecurityManager.checkAccess(this)</code>.
415 * @throws SecurityException if the current Thread cannot modify this Thread
416 * @see SecurityManager#checkAccess(Thread)
418 public final void checkAccess()
420 SecurityManager sm = System.getSecurityManager();
422 sm.checkAccess(this);
426 * Count the number of stack frames in this Thread. The Thread in question
427 * must be suspended when this occurs.
429 * @return the number of stack frames in this Thread
430 * @throws IllegalThreadStateException if this Thread is not suspended
431 * @deprecated pointless, since suspend is deprecated
433 public native int countStackFrames();
436 * Get the currently executing Thread.
438 * @return the currently executing Thread
440 public static native Thread currentThread();
443 * Originally intended to destroy this thread, this method was never
444 * implemented by Sun, and is hence a no-op.
446 public void destroy()
448 throw new NoSuchMethodError();
452 * Print a stack trace of the current thread to stderr using the same
453 * format as Throwable's printStackTrace() method.
455 * @see Throwable#printStackTrace()
457 public static void dumpStack()
459 (new Exception("Stack trace")).printStackTrace();
463 * Copy every active thread in the current Thread's ThreadGroup into the
464 * array. Extra threads are silently ignored. This implementation calls
465 * <code>getThreadGroup().enumerate(array)</code>, which may have a
466 * security check, <code>checkAccess(group)</code>.
468 * @param array the array to place the Threads into
469 * @return the number of Threads placed into the array
470 * @throws NullPointerException if array is null
471 * @throws SecurityException if you cannot access the ThreadGroup
472 * @see ThreadGroup#enumerate(Thread[])
473 * @see #activeCount()
474 * @see SecurityManager#checkAccess(ThreadGroup)
476 public static int enumerate(Thread[] array)
478 return currentThread().group.enumerate(array);
482 * Get this Thread's name.
484 * @return this Thread's name
486 public final String getName()
492 * Get this Thread's priority.
494 * @return the Thread's priority
496 public final int getPriority()
502 * Get the ThreadGroup this Thread belongs to. If the thread has died, this
505 * @return this Thread's ThreadGroup
507 public final ThreadGroup getThreadGroup()
513 * Checks whether the current thread holds the monitor on a given object.
514 * This allows you to do <code>assert Thread.holdsLock(obj)</code>.
516 * @param obj the object to test lock ownership on.
517 * @return true if the current thread is currently synchronized on obj
518 * @throws NullPointerException if obj is null
521 public static native boolean holdsLock(Object obj);
524 * Interrupt this Thread. First, there is a security check,
525 * <code>checkAccess</code>. Then, depending on the current state of the
526 * thread, various actions take place:
528 * <p>If the thread is waiting because of {@link #wait()},
529 * {@link #sleep(long)}, or {@link #join()}, its <i>interrupt status</i>
530 * will be cleared, and an InterruptedException will be thrown. Notice that
531 * this case is only possible if an external thread called interrupt().
533 * <p>If the thread is blocked in an interruptible I/O operation, in
534 * {@link java.nio.channels.InterruptibleChannel}, the <i>interrupt
535 * status</i> will be set, and ClosedByInterruptException will be thrown.
537 * <p>If the thread is blocked on a {@link java.nio.channels.Selector}, the
538 * <i>interrupt status</i> will be set, and the selection will return, with
539 * a possible non-zero value, as though by the wakeup() method.
541 * <p>Otherwise, the interrupt status will be set.
543 * @throws SecurityException if you cannot modify this Thread
545 public native void interrupt();
548 * Determine whether the current Thread has been interrupted, and clear
549 * the <i>interrupted status</i> in the process.
551 * @return whether the current Thread has been interrupted
552 * @see #isInterrupted()
554 public static boolean interrupted()
556 return currentThread().isInterrupted(true);
560 * Determine whether the given Thread has been interrupted, but leave
561 * the <i>interrupted status</i> alone in the process.
563 * @return whether the Thread has been interrupted
564 * @see #interrupted()
566 public boolean isInterrupted()
568 return interrupt_flag;
572 * Determine whether this Thread is alive. A thread which is alive has
573 * started and not yet died.
575 * @return whether this Thread is alive
577 public final synchronized boolean isAlive()
583 * Tell whether this is a daemon Thread or not.
585 * @return whether this is a daemon Thread or not
586 * @see #setDaemon(boolean)
588 public final boolean isDaemon()
594 * Wait forever for the Thread in question to die.
596 * @throws InterruptedException if the Thread is interrupted; it's
597 * <i>interrupted status</i> will be cleared
599 public final void join() throws InterruptedException
605 * Wait the specified amount of time for the Thread in question to die.
607 * @param ms the number of milliseconds to wait, or 0 for forever
608 * @throws InterruptedException if the Thread is interrupted; it's
609 * <i>interrupted status</i> will be cleared
611 public final void join(long ms) throws InterruptedException
617 * Wait the specified amount of time for the Thread in question to die.
619 * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
620 * not offer that fine a grain of timing resolution. Besides, there is
621 * no guarantee that this thread can start up immediately when time expires,
622 * because some other thread may be active. So don't expect real-time
625 * @param ms the number of milliseconds to wait, or 0 for forever
626 * @param ns the number of extra nanoseconds to sleep (0-999999)
627 * @throws InterruptedException if the Thread is interrupted; it's
628 * <i>interrupted status</i> will be cleared
629 * @throws IllegalArgumentException if ns is invalid
630 * @XXX A ThreadListener would be nice, to make this efficient.
632 public final native void join(long ms, int ns)
633 throws InterruptedException;
636 * Resume a suspended thread.
638 * @throws SecurityException if you cannot resume the Thread
639 * @see #checkAccess()
641 * @deprecated pointless, since suspend is deprecated
643 public final native void resume();
645 private final native void finish_();
648 * Determine whether the given Thread has been interrupted, but leave
649 * the <i>interrupted status</i> alone in the process.
651 * @return whether the current Thread has been interrupted
652 * @see #interrupted()
654 private boolean isInterrupted(boolean clear_flag)
656 boolean r = interrupt_flag;
659 // Only clear the flag if we saw it as set. Otherwise this could
660 // potentially cause us to miss an interrupt in a race condition,
661 // because this method is not synchronized.
662 interrupt_flag = false;
668 * The method of Thread that will be run if there is no Runnable object
669 * associated with the Thread. Thread's implementation does nothing at all.
672 * @see #Thread(ThreadGroup, Runnable, String)
676 if (runnable != null)
681 * Set the daemon status of this Thread. If this is a daemon Thread, then
682 * the VM may exit even if it is still running. This may only be called
683 * before the Thread starts running. There may be a security check,
684 * <code>checkAccess</code>.
686 * @param daemon whether this should be a daemon thread or not
687 * @throws SecurityException if you cannot modify this Thread
688 * @throws IllegalThreadStateException if the Thread is active
690 * @see #checkAccess()
692 public final void setDaemon(boolean daemon)
695 throw new IllegalThreadStateException();
697 this.daemon = daemon;
701 * Returns the context classloader of this Thread. The context
702 * classloader can be used by code that want to load classes depending
703 * on the current thread. Normally classes are loaded depending on
704 * the classloader of the current class. There may be a security check
705 * for <code>RuntimePermission("getClassLoader")</code> if the caller's
706 * class loader is not null or an ancestor of this thread's context class
709 * @return the context class loader
710 * @throws SecurityException when permission is denied
711 * @see setContextClassLoader(ClassLoader)
714 public synchronized ClassLoader getContextClassLoader()
716 if (contextClassLoader == null)
717 contextClassLoader = ClassLoader.getSystemClassLoader();
719 SecurityManager sm = System.getSecurityManager();
720 // FIXME: we can't currently find the caller's class loader.
721 ClassLoader callers = null;
722 if (sm != null && callers != null)
724 // See if the caller's class loader is the same as or an
725 // ancestor of this thread's class loader.
726 while (callers != null && callers != contextClassLoader)
728 // FIXME: should use some internal version of getParent
729 // that avoids security checks.
730 callers = callers.getParent();
733 if (callers != contextClassLoader)
734 sm.checkPermission(new RuntimePermission("getClassLoader"));
737 return contextClassLoader;
741 * Sets the context classloader for this Thread. When not explicitly set,
742 * the context classloader for a thread is the same as the context
743 * classloader of the thread that created this thread. The first thread has
744 * as context classloader the system classloader. There may be a security
745 * check for <code>RuntimePermission("setContextClassLoader")</code>.
747 * @param classloader the new context class loader
748 * @throws SecurityException when permission is denied
749 * @see getContextClassLoader()
752 public synchronized void setContextClassLoader(ClassLoader classloader)
754 SecurityManager sm = System.getSecurityManager();
756 sm.checkPermission(new RuntimePermission("setContextClassLoader"));
757 this.contextClassLoader = classloader;
761 * Set this Thread's name. There may be a security check,
762 * <code>checkAccess</code>.
764 * @param name the new name for this Thread
765 * @throws NullPointerException if name is null
766 * @throws SecurityException if you cannot modify this Thread
768 public final void setName(String name)
771 // The Class Libraries book says ``threadName cannot be null''. I
772 // take this to mean NullPointerException.
774 throw new NullPointerException();
779 * Causes the currently executing thread object to temporarily pause
780 * and allow other threads to execute.
782 public static native void yield();
785 * Suspend the current Thread's execution for the specified amount of
786 * time. The Thread will not lose any locks it has during this time. There
787 * are no guarantees which thread will be next to run, but most VMs will
788 * choose the highest priority thread that has been waiting longest.
790 * @param ms the number of milliseconds to sleep, or 0 for forever
791 * @throws InterruptedException if the Thread is interrupted; it's
792 * <i>interrupted status</i> will be cleared
796 public static void sleep(long ms) throws InterruptedException
802 * Suspend the current Thread's execution for the specified amount of
803 * time. The Thread will not lose any locks it has during this time. There
804 * are no guarantees which thread will be next to run, but most VMs will
805 * choose the highest priority thread that has been waiting longest.
807 * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
808 * not offer that fine a grain of timing resolution. Besides, there is
809 * no guarantee that this thread can start up immediately when time expires,
810 * because some other thread may be active. So don't expect real-time
813 * @param ms the number of milliseconds to sleep, or 0 for forever
814 * @param ns the number of extra nanoseconds to sleep (0-999999)
815 * @throws InterruptedException if the Thread is interrupted; it's
816 * <i>interrupted status</i> will be cleared
817 * @throws IllegalArgumentException if ns is invalid
819 * @see #wait(long, int)
821 public static native void sleep(long timeout, int nanos)
822 throws InterruptedException;
825 * Start this Thread, calling the run() method of the Runnable this Thread
826 * was created with, or else the run() method of the Thread itself. This
827 * is the only way to start a new thread; calling run by yourself will just
828 * stay in the same thread. The virtual machine will remove the thread from
829 * its thread group when the run() method completes.
831 * @throws IllegalThreadStateException if the thread has already started
834 public native void start();
837 * Cause this Thread to stop abnormally because of the throw of a ThreadDeath
838 * error. If you stop a Thread that has not yet started, it will stop
839 * immediately when it is actually started.
841 * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
842 * leave data in bad states. Hence, there is a security check:
843 * <code>checkAccess(this)</code>, plus another one if the current thread
844 * is not this: <code>RuntimePermission("stopThread")</code>. If you must
845 * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
846 * ThreadDeath is the only exception which does not print a stack trace when
849 * @throws SecurityException if you cannot stop the Thread
851 * @see #checkAccess()
854 * @see ThreadGroup#uncaughtException(Thread, Throwable)
855 * @see SecurityManager#checkAccess(Thread)
856 * @see SecurityManager#checkPermission(Permission)
857 * @deprecated unsafe operation, try not to use
859 public final void stop()
861 // Argument doesn't matter, because this is no longer
867 * Cause this Thread to stop abnormally and throw the specified exception.
868 * If you stop a Thread that has not yet started, it will stop immediately
869 * when it is actually started. <b>WARNING</b>This bypasses Java security,
870 * and can throw a checked exception which the call stack is unprepared to
871 * handle. Do not abuse this power.
873 * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
874 * leave data in bad states. Hence, there is a security check:
875 * <code>checkAccess(this)</code>, plus another one if the current thread
876 * is not this: <code>RuntimePermission("stopThread")</code>. If you must
877 * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
878 * ThreadDeath is the only exception which does not print a stack trace when
881 * @param t the Throwable to throw when the Thread dies
882 * @throws SecurityException if you cannot stop the Thread
883 * @throws NullPointerException in the calling thread, if t is null
885 * @see #checkAccess()
888 * @see ThreadGroup#uncaughtException(Thread, Throwable)
889 * @see SecurityManager#checkAccess(Thread)
890 * @see SecurityManager#checkPermission(Permission)
891 * @deprecated unsafe operation, try not to use
893 public final native void stop(Throwable t);
896 * Suspend this Thread. It will not come back, ever, unless it is resumed.
898 * <p>This is inherently unsafe, as the suspended thread still holds locks,
899 * and can potentially deadlock your program. Hence, there is a security
900 * check: <code>checkAccess</code>.
902 * @throws SecurityException if you cannot suspend the Thread
903 * @see #checkAccess()
905 * @deprecated unsafe operation, try not to use
907 public final native void suspend();
910 * Set this Thread's priority. There may be a security check,
911 * <code>checkAccess</code>, then the priority is set to the smaller of
912 * priority and the ThreadGroup maximum priority.
914 * @param priority the new priority for this Thread
915 * @throws IllegalArgumentException if priority exceeds MIN_PRIORITY or
917 * @throws SecurityException if you cannot modify this Thread
918 * @see #getPriority()
919 * @see #checkAccess()
920 * @see ThreadGroup#getMaxPriority()
924 public final native void setPriority(int newPriority);
927 * Returns a string representation of this thread, including the
928 * thread's name, priority, and thread group.
930 * @return a human-readable String representing this Thread
932 public String toString()
934 return ("Thread[" + name + "," + priority + ","
935 + (group == null ? "" : group.getName()) + "]");
938 private final native void initialize_native();
940 private final native static String gen_name();
943 * Returns the map used by ThreadLocal to store the thread local values.
945 static Map getThreadLocals()
947 Thread thread = currentThread();
948 Map locals = thread.locals;
951 locals = thread.locals = new WeakIdentityHashMap();
957 * Assigns the given <code>UncaughtExceptionHandler</code> to this
958 * thread. This will then be called if the thread terminates due
959 * to an uncaught exception, pre-empting that of the
960 * <code>ThreadGroup</code>.
962 * @param h the handler to use for this thread.
963 * @throws SecurityException if the current thread can't modify this thread.
966 public void setUncaughtExceptionHandler(UncaughtExceptionHandler h)
968 SecurityManager sm = SecurityManager.current; // Be thread-safe.
970 sm.checkAccess(this);
971 exceptionHandler = h;
976 * Returns the handler used when this thread terminates due to an
977 * uncaught exception. The handler used is determined by the following:
980 * <li>If this thread has its own handler, this is returned.</li>
981 * <li>If not, then the handler of the thread's <code>ThreadGroup</code>
982 * object is returned.</li>
983 * <li>If both are unavailable, then <code>null</code> is returned
984 * (which can only happen when the thread was terminated since
985 * then it won't have an associated thread group anymore).</li>
988 * @return the appropriate <code>UncaughtExceptionHandler</code> or
989 * <code>null</code> if one can't be obtained.
992 public UncaughtExceptionHandler getUncaughtExceptionHandler()
994 return exceptionHandler != null ? exceptionHandler : group;
999 * Sets the default uncaught exception handler used when one isn't
1000 * provided by the thread or its associated <code>ThreadGroup</code>.
1001 * This exception handler is used when the thread itself does not
1002 * have an exception handler, and the thread's <code>ThreadGroup</code>
1003 * does not override this default mechanism with its own. As the group
1004 * calls this handler by default, this exception handler should not defer
1005 * to that of the group, as it may lead to infinite recursion.
1008 * Uncaught exception handlers are used when a thread terminates due to
1009 * an uncaught exception. Replacing this handler allows default code to
1010 * be put in place for all threads in order to handle this eventuality.
1013 * @param h the new default uncaught exception handler to use.
1014 * @throws SecurityException if a security manager is present and
1015 * disallows the runtime permission
1016 * "setDefaultUncaughtExceptionHandler".
1020 setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler h)
1022 SecurityManager sm = SecurityManager.current; // Be thread-safe.
1024 sm.checkPermission(new RuntimePermission("setDefaultUncaughtExceptionHandler"));
1029 * Returns the handler used by default when a thread terminates
1030 * unexpectedly due to an exception, or <code>null</code> if one doesn't
1033 * @return the default uncaught exception handler.
1036 public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
1038 return defaultHandler;
1042 * Returns the unique identifier for this thread. This ID is generated
1043 * on thread creation, and may be re-used on its death.
1045 * @return a positive long number representing the thread's ID.
1055 * This interface is used to handle uncaught exceptions
1056 * which cause a <code>Thread</code> to terminate. When
1057 * a thread, t, is about to terminate due to an uncaught
1058 * exception, the virtual machine looks for a class which
1059 * implements this interface, in order to supply it with
1060 * the dying thread and its uncaught exception.
1063 * The virtual machine makes two attempts to find an
1064 * appropriate handler for the uncaught exception, in
1065 * the following order:
1069 * <code>t.getUncaughtExceptionHandler()</code> --
1070 * the dying thread is queried first for a handler
1071 * specific to that thread.
1074 * <code>t.getThreadGroup()</code> --
1075 * the thread group of the dying thread is used to
1076 * handle the exception. If the thread group has
1077 * no special requirements for handling the exception,
1078 * it may simply forward it on to
1079 * <code>Thread.getDefaultUncaughtExceptionHandler()</code>,
1080 * the default handler, which is used as a last resort.
1084 * The first handler found is the one used to handle
1085 * the uncaught exception.
1088 * @author Tom Tromey <tromey@redhat.com>
1089 * @author Andrew John Hughes <gnu_andrew@member.fsf.org>
1091 * @see Thread#getUncaughtExceptionHandler()
1092 * @see Thread#setUncaughtExceptionHander(java.lang.Thread.UncaughtExceptionHandler)
1093 * @see Thread#getDefaultUncaughtExceptionHandler()
1095 * Thread#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)
1097 public interface UncaughtExceptionHandler
1100 * Invoked by the virtual machine with the dying thread
1101 * and the uncaught exception. Any exceptions thrown
1102 * by this method are simply ignored by the virtual
1105 * @param thr the dying thread.
1106 * @param exc the uncaught exception.
1108 void uncaughtException(Thread thr, Throwable exc);