Merge from mainline.
[official-gcc.git] / libjava / java / lang / Thread.java
blob505b99baf20b66ea380bda7a3e0a21c010088fea
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)
10 any later version.
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
20 02110-1301 USA.
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
25 combination.
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. */
40 package java.lang;
42 import gnu.gcj.RawData;
43 import gnu.gcj.RawDataManaged;
44 import gnu.java.util.WeakIdentityHashMap;
45 import java.util.Map;
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.
55 /**
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.
83 * @author Tom Tromey
84 * @author John Keiser
85 * @author Eric Blake (ebb9@email.byu.edu)
86 * @see Runnable
87 * @see Runtime#exit(int)
88 * @see #run()
89 * @see #start()
90 * @see ThreadLocal
91 * @since 1.0
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.
109 ThreadGroup group;
111 /** The object to run(), null if this is the target. */
112 private Runnable runnable;
114 /** The thread name, non-null. */
115 String name;
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 /** The default exception handler. */
131 private static UncaughtExceptionHandler defaultHandler;
133 /** Thread local storage. Package accessible for use by
134 * InheritableThreadLocal.
136 WeakIdentityHashMap locals;
138 /** The uncaught exception handler. */
139 UncaughtExceptionHandler exceptionHandler;
141 // This describes the top-most interpreter frame for this thread.
142 RawData interp_frame;
144 // Our native data - points to an instance of struct natThread.
145 private RawDataManaged data;
148 * Allocates a new <code>Thread</code> object. This constructor has
149 * the same effect as <code>Thread(null, null,</code>
150 * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
151 * a newly generated name. Automatically generated names are of the
152 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
153 * <p>
154 * Threads created this way must have overridden their
155 * <code>run()</code> method to actually do anything. An example
156 * illustrating this method being used follows:
157 * <p><blockquote><pre>
158 * import java.lang.*;
160 * class plain01 implements Runnable {
161 * String name;
162 * plain01() {
163 * name = null;
165 * plain01(String s) {
166 * name = s;
168 * public void run() {
169 * if (name == null)
170 * System.out.println("A new thread created");
171 * else
172 * System.out.println("A new thread with name " + name +
173 * " created");
176 * class threadtest01 {
177 * public static void main(String args[] ) {
178 * int failed = 0 ;
180 * <b>Thread t1 = new Thread();</b>
181 * if (t1 != null)
182 * System.out.println("new Thread() succeed");
183 * else {
184 * System.out.println("new Thread() failed");
185 * failed++;
189 * </pre></blockquote>
191 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
192 * java.lang.Runnable, java.lang.String)
194 public Thread()
196 this(null, null, gen_name());
200 * Allocates a new <code>Thread</code> object. This constructor has
201 * the same effect as <code>Thread(null, target,</code>
202 * <i>gname</i><code>)</code>, where <i>gname</i> is
203 * a newly generated name. Automatically generated names are of the
204 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
206 * @param target the object whose <code>run</code> method is called.
207 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
208 * java.lang.Runnable, java.lang.String)
210 public Thread(Runnable target)
212 this(null, target, gen_name());
216 * Allocates a new <code>Thread</code> object. This constructor has
217 * the same effect as <code>Thread(null, null, name)</code>.
219 * @param name the name of the new thread.
220 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
221 * java.lang.Runnable, java.lang.String)
223 public Thread(String name)
225 this(null, null, name);
229 * Allocates a new <code>Thread</code> object. This constructor has
230 * the same effect as <code>Thread(group, target,</code>
231 * <i>gname</i><code>)</code>, where <i>gname</i> is
232 * a newly generated name. Automatically generated names are of the
233 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
235 * @param group the group to put the Thread into
236 * @param target the Runnable object to execute
237 * @throws SecurityException if this thread cannot access <code>group</code>
238 * @throws IllegalThreadStateException if group is destroyed
239 * @see #Thread(ThreadGroup, Runnable, String)
241 public Thread(ThreadGroup group, Runnable target)
243 this(group, target, gen_name());
247 * Allocates a new <code>Thread</code> object. This constructor has
248 * the same effect as <code>Thread(group, null, name)</code>
250 * @param group the group to put the Thread into
251 * @param name the name for the Thread
252 * @throws NullPointerException if name is null
253 * @throws SecurityException if this thread cannot access <code>group</code>
254 * @throws IllegalThreadStateException if group is destroyed
255 * @see #Thread(ThreadGroup, Runnable, String)
257 public Thread(ThreadGroup group, String name)
259 this(group, null, name);
263 * Allocates a new <code>Thread</code> object. This constructor has
264 * the same effect as <code>Thread(null, target, name)</code>.
266 * @param target the Runnable object to execute
267 * @param name the name for the Thread
268 * @throws NullPointerException if name is null
269 * @see #Thread(ThreadGroup, Runnable, String)
271 public Thread(Runnable target, String name)
273 this(null, target, name);
277 * Allocate a new Thread object, with the specified ThreadGroup and name, and
278 * using the specified Runnable object's <code>run()</code> method to
279 * execute. If the Runnable object is null, <code>this</code> (which is
280 * a Runnable) is used instead.
282 * <p>If the ThreadGroup is null, the security manager is checked. If a
283 * manager exists and returns a non-null object for
284 * <code>getThreadGroup</code>, that group is used; otherwise the group
285 * of the creating thread is used. Note that the security manager calls
286 * <code>checkAccess</code> if the ThreadGroup is not null.
288 * <p>The new Thread will inherit its creator's priority and daemon status.
289 * These can be changed with <code>setPriority</code> and
290 * <code>setDaemon</code>.
292 * @param group the group to put the Thread into
293 * @param target the Runnable object to execute
294 * @param name the name for the Thread
295 * @throws NullPointerException if name is null
296 * @throws SecurityException if this thread cannot access <code>group</code>
297 * @throws IllegalThreadStateException if group is destroyed
298 * @see Runnable#run()
299 * @see #run()
300 * @see #setDaemon(boolean)
301 * @see #setPriority(int)
302 * @see SecurityManager#checkAccess(ThreadGroup)
303 * @see ThreadGroup#checkAccess()
305 public Thread(ThreadGroup group, Runnable target, String name)
307 this(currentThread(), group, target, name);
311 * Allocate a new Thread object, as if by
312 * <code>Thread(group, null, name)</code>, and give it the specified stack
313 * size, in bytes. The stack size is <b>highly platform independent</b>,
314 * and the virtual machine is free to round up or down, or ignore it
315 * completely. A higher value might let you go longer before a
316 * <code>StackOverflowError</code>, while a lower value might let you go
317 * longer before an <code>OutOfMemoryError</code>. Or, it may do absolutely
318 * nothing! So be careful, and expect to need to tune this value if your
319 * virtual machine even supports it.
321 * @param group the group to put the Thread into
322 * @param target the Runnable object to execute
323 * @param name the name for the Thread
324 * @param size the stack size, in bytes; 0 to be ignored
325 * @throws NullPointerException if name is null
326 * @throws SecurityException if this thread cannot access <code>group</code>
327 * @throws IllegalThreadStateException if group is destroyed
328 * @since 1.4
330 public Thread(ThreadGroup group, Runnable target, String name, long size)
332 // Just ignore stackSize for now.
333 this(currentThread(), group, target, name);
336 private Thread (Thread current, ThreadGroup g, Runnable r, String n)
338 // Make sure the current thread may create a new thread.
339 checkAccess();
341 // The Class Libraries book says ``threadName cannot be null''. I
342 // take this to mean NullPointerException.
343 if (n == null)
344 throw new NullPointerException ();
346 if (g == null)
348 // If CURRENT is null, then we are bootstrapping the first thread.
349 // Use ThreadGroup.root, the main threadgroup.
350 if (current == null)
351 group = ThreadGroup.root;
352 else
353 group = current.getThreadGroup();
355 else
356 group = g;
358 data = null;
359 interrupt_flag = false;
360 alive_flag = false;
361 startable_flag = true;
363 if (current != null)
365 group.checkAccess();
367 daemon = current.isDaemon();
368 int gmax = group.getMaxPriority();
369 int pri = current.getPriority();
370 priority = (gmax < pri ? gmax : pri);
371 contextClassLoader = current.contextClassLoader;
372 InheritableThreadLocal.newChildThread(this);
374 else
376 daemon = false;
377 priority = NORM_PRIORITY;
380 name = n;
381 group.addThread(this);
382 runnable = r;
384 initialize_native ();
388 * Get the number of active threads in the current Thread's ThreadGroup.
389 * This implementation calls
390 * <code>currentThread().getThreadGroup().activeCount()</code>.
392 * @return the number of active threads in the current ThreadGroup
393 * @see ThreadGroup#activeCount()
395 public static int activeCount()
397 return currentThread().group.activeCount();
401 * Check whether the current Thread is allowed to modify this Thread. This
402 * passes the check on to <code>SecurityManager.checkAccess(this)</code>.
404 * @throws SecurityException if the current Thread cannot modify this Thread
405 * @see SecurityManager#checkAccess(Thread)
407 public final void checkAccess()
409 SecurityManager sm = System.getSecurityManager();
410 if (sm != null)
411 sm.checkAccess(this);
415 * Count the number of stack frames in this Thread. The Thread in question
416 * must be suspended when this occurs.
418 * @return the number of stack frames in this Thread
419 * @throws IllegalThreadStateException if this Thread is not suspended
420 * @deprecated pointless, since suspend is deprecated
422 public native int countStackFrames();
425 * Get the currently executing Thread.
427 * @return the currently executing Thread
429 public static native Thread currentThread();
432 * Originally intended to destroy this thread, this method was never
433 * implemented by Sun, and is hence a no-op.
435 public void destroy()
437 throw new NoSuchMethodError();
441 * Print a stack trace of the current thread to stderr using the same
442 * format as Throwable's printStackTrace() method.
444 * @see Throwable#printStackTrace()
446 public static void dumpStack()
448 (new Exception("Stack trace")).printStackTrace();
452 * Copy every active thread in the current Thread's ThreadGroup into the
453 * array. Extra threads are silently ignored. This implementation calls
454 * <code>getThreadGroup().enumerate(array)</code>, which may have a
455 * security check, <code>checkAccess(group)</code>.
457 * @param array the array to place the Threads into
458 * @return the number of Threads placed into the array
459 * @throws NullPointerException if array is null
460 * @throws SecurityException if you cannot access the ThreadGroup
461 * @see ThreadGroup#enumerate(Thread[])
462 * @see #activeCount()
463 * @see SecurityManager#checkAccess(ThreadGroup)
465 public static int enumerate(Thread[] array)
467 return currentThread().group.enumerate(array);
471 * Get this Thread's name.
473 * @return this Thread's name
475 public final String getName()
477 return name;
481 * Get this Thread's priority.
483 * @return the Thread's priority
485 public final int getPriority()
487 return priority;
491 * Get the ThreadGroup this Thread belongs to. If the thread has died, this
492 * returns null.
494 * @return this Thread's ThreadGroup
496 public final ThreadGroup getThreadGroup()
498 return group;
502 * Checks whether the current thread holds the monitor on a given object.
503 * This allows you to do <code>assert Thread.holdsLock(obj)</code>.
505 * @param obj the object to test lock ownership on.
506 * @return true if the current thread is currently synchronized on obj
507 * @throws NullPointerException if obj is null
508 * @since 1.4
510 public static native boolean holdsLock(Object obj);
513 * Interrupt this Thread. First, there is a security check,
514 * <code>checkAccess</code>. Then, depending on the current state of the
515 * thread, various actions take place:
517 * <p>If the thread is waiting because of {@link #wait()},
518 * {@link #sleep(long)}, or {@link #join()}, its <i>interrupt status</i>
519 * will be cleared, and an InterruptedException will be thrown. Notice that
520 * this case is only possible if an external thread called interrupt().
522 * <p>If the thread is blocked in an interruptible I/O operation, in
523 * {@link java.nio.channels.InterruptibleChannel}, the <i>interrupt
524 * status</i> will be set, and ClosedByInterruptException will be thrown.
526 * <p>If the thread is blocked on a {@link java.nio.channels.Selector}, the
527 * <i>interrupt status</i> will be set, and the selection will return, with
528 * a possible non-zero value, as though by the wakeup() method.
530 * <p>Otherwise, the interrupt status will be set.
532 * @throws SecurityException if you cannot modify this Thread
534 public native void interrupt();
537 * Determine whether the current Thread has been interrupted, and clear
538 * the <i>interrupted status</i> in the process.
540 * @return whether the current Thread has been interrupted
541 * @see #isInterrupted()
543 public static boolean interrupted()
545 return currentThread().isInterrupted(true);
549 * Determine whether the given Thread has been interrupted, but leave
550 * the <i>interrupted status</i> alone in the process.
552 * @return whether the Thread has been interrupted
553 * @see #interrupted()
555 public boolean isInterrupted()
557 return interrupt_flag;
561 * Determine whether this Thread is alive. A thread which is alive has
562 * started and not yet died.
564 * @return whether this Thread is alive
566 public final synchronized boolean isAlive()
568 return alive_flag;
572 * Tell whether this is a daemon Thread or not.
574 * @return whether this is a daemon Thread or not
575 * @see #setDaemon(boolean)
577 public final boolean isDaemon()
579 return daemon;
583 * Wait forever for the Thread in question to die.
585 * @throws InterruptedException if the Thread is interrupted; it's
586 * <i>interrupted status</i> will be cleared
588 public final void join() throws InterruptedException
590 join(0, 0);
594 * Wait the specified amount of time for the Thread in question to die.
596 * @param ms the number of milliseconds to wait, or 0 for forever
597 * @throws InterruptedException if the Thread is interrupted; it's
598 * <i>interrupted status</i> will be cleared
600 public final void join(long ms) throws InterruptedException
602 join(ms, 0);
606 * Wait the specified amount of time for the Thread in question to die.
608 * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
609 * not offer that fine a grain of timing resolution. Besides, there is
610 * no guarantee that this thread can start up immediately when time expires,
611 * because some other thread may be active. So don't expect real-time
612 * performance.
614 * @param ms the number of milliseconds to wait, or 0 for forever
615 * @param ns the number of extra nanoseconds to sleep (0-999999)
616 * @throws InterruptedException if the Thread is interrupted; it's
617 * <i>interrupted status</i> will be cleared
618 * @throws IllegalArgumentException if ns is invalid
619 * @XXX A ThreadListener would be nice, to make this efficient.
621 public final native void join(long ms, int ns)
622 throws InterruptedException;
625 * Resume a suspended thread.
627 * @throws SecurityException if you cannot resume the Thread
628 * @see #checkAccess()
629 * @see #suspend()
630 * @deprecated pointless, since suspend is deprecated
632 public final native void resume();
634 private final native void finish_();
637 * Determine whether the given Thread has been interrupted, but leave
638 * the <i>interrupted status</i> alone in the process.
640 * @return whether the current Thread has been interrupted
641 * @see #interrupted()
643 private boolean isInterrupted(boolean clear_flag)
645 boolean r = interrupt_flag;
646 if (clear_flag && r)
648 // Only clear the flag if we saw it as set. Otherwise this could
649 // potentially cause us to miss an interrupt in a race condition,
650 // because this method is not synchronized.
651 interrupt_flag = false;
653 return r;
657 * The method of Thread that will be run if there is no Runnable object
658 * associated with the Thread. Thread's implementation does nothing at all.
660 * @see #start()
661 * @see #Thread(ThreadGroup, Runnable, String)
663 public void run()
665 if (runnable != null)
666 runnable.run();
670 * Set the daemon status of this Thread. If this is a daemon Thread, then
671 * the VM may exit even if it is still running. This may only be called
672 * before the Thread starts running. There may be a security check,
673 * <code>checkAccess</code>.
675 * @param daemon whether this should be a daemon thread or not
676 * @throws SecurityException if you cannot modify this Thread
677 * @throws IllegalThreadStateException if the Thread is active
678 * @see #isDaemon()
679 * @see #checkAccess()
681 public final void setDaemon(boolean daemon)
683 if (!startable_flag)
684 throw new IllegalThreadStateException();
685 checkAccess();
686 this.daemon = daemon;
690 * Returns the context classloader of this Thread. The context
691 * classloader can be used by code that want to load classes depending
692 * on the current thread. Normally classes are loaded depending on
693 * the classloader of the current class. There may be a security check
694 * for <code>RuntimePermission("getClassLoader")</code> if the caller's
695 * class loader is not null or an ancestor of this thread's context class
696 * loader.
698 * @return the context class loader
699 * @throws SecurityException when permission is denied
700 * @see setContextClassLoader(ClassLoader)
701 * @since 1.2
703 public synchronized ClassLoader getContextClassLoader()
705 if (contextClassLoader == null)
706 contextClassLoader = ClassLoader.getSystemClassLoader();
708 SecurityManager sm = System.getSecurityManager();
709 // FIXME: we can't currently find the caller's class loader.
710 ClassLoader callers = null;
711 if (sm != null && callers != null)
713 // See if the caller's class loader is the same as or an
714 // ancestor of this thread's class loader.
715 while (callers != null && callers != contextClassLoader)
717 // FIXME: should use some internal version of getParent
718 // that avoids security checks.
719 callers = callers.getParent();
722 if (callers != contextClassLoader)
723 sm.checkPermission(new RuntimePermission("getClassLoader"));
726 return contextClassLoader;
730 * Sets the context classloader for this Thread. When not explicitly set,
731 * the context classloader for a thread is the same as the context
732 * classloader of the thread that created this thread. The first thread has
733 * as context classloader the system classloader. There may be a security
734 * check for <code>RuntimePermission("setContextClassLoader")</code>.
736 * @param classloader the new context class loader
737 * @throws SecurityException when permission is denied
738 * @see getContextClassLoader()
739 * @since 1.2
741 public synchronized void setContextClassLoader(ClassLoader classloader)
743 SecurityManager sm = System.getSecurityManager();
744 if (sm != null)
745 sm.checkPermission(new RuntimePermission("setContextClassLoader"));
746 this.contextClassLoader = classloader;
750 * Set this Thread's name. There may be a security check,
751 * <code>checkAccess</code>.
753 * @param name the new name for this Thread
754 * @throws NullPointerException if name is null
755 * @throws SecurityException if you cannot modify this Thread
757 public final void setName(String name)
759 checkAccess();
760 // The Class Libraries book says ``threadName cannot be null''. I
761 // take this to mean NullPointerException.
762 if (name == null)
763 throw new NullPointerException();
764 this.name = name;
768 * Causes the currently executing thread object to temporarily pause
769 * and allow other threads to execute.
771 public static native void yield();
774 * Suspend the current Thread's execution for the specified amount of
775 * time. The Thread will not lose any locks it has during this time. There
776 * are no guarantees which thread will be next to run, but most VMs will
777 * choose the highest priority thread that has been waiting longest.
779 * @param ms the number of milliseconds to sleep, or 0 for forever
780 * @throws InterruptedException if the Thread is interrupted; it's
781 * <i>interrupted status</i> will be cleared
782 * @see #notify()
783 * @see #wait(long)
785 public static void sleep(long ms) throws InterruptedException
787 sleep(ms, 0);
791 * Suspend the current Thread's execution for the specified amount of
792 * time. The Thread will not lose any locks it has during this time. There
793 * are no guarantees which thread will be next to run, but most VMs will
794 * choose the highest priority thread that has been waiting longest.
796 * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
797 * not offer that fine a grain of timing resolution. Besides, there is
798 * no guarantee that this thread can start up immediately when time expires,
799 * because some other thread may be active. So don't expect real-time
800 * performance.
802 * @param ms the number of milliseconds to sleep, or 0 for forever
803 * @param ns the number of extra nanoseconds to sleep (0-999999)
804 * @throws InterruptedException if the Thread is interrupted; it's
805 * <i>interrupted status</i> will be cleared
806 * @throws IllegalArgumentException if ns is invalid
807 * @see #notify()
808 * @see #wait(long, int)
810 public static native void sleep(long timeout, int nanos)
811 throws InterruptedException;
814 * Start this Thread, calling the run() method of the Runnable this Thread
815 * was created with, or else the run() method of the Thread itself. This
816 * is the only way to start a new thread; calling run by yourself will just
817 * stay in the same thread. The virtual machine will remove the thread from
818 * its thread group when the run() method completes.
820 * @throws IllegalThreadStateException if the thread has already started
821 * @see #run()
823 public native void start();
826 * Cause this Thread to stop abnormally because of the throw of a ThreadDeath
827 * error. If you stop a Thread that has not yet started, it will stop
828 * immediately when it is actually started.
830 * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
831 * leave data in bad states. Hence, there is a security check:
832 * <code>checkAccess(this)</code>, plus another one if the current thread
833 * is not this: <code>RuntimePermission("stopThread")</code>. If you must
834 * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
835 * ThreadDeath is the only exception which does not print a stack trace when
836 * the thread dies.
838 * @throws SecurityException if you cannot stop the Thread
839 * @see #interrupt()
840 * @see #checkAccess()
841 * @see #start()
842 * @see ThreadDeath
843 * @see ThreadGroup#uncaughtException(Thread, Throwable)
844 * @see SecurityManager#checkAccess(Thread)
845 * @see SecurityManager#checkPermission(Permission)
846 * @deprecated unsafe operation, try not to use
848 public final void stop()
850 // Argument doesn't matter, because this is no longer
851 // supported.
852 stop(null);
856 * Cause this Thread to stop abnormally and throw the specified exception.
857 * If you stop a Thread that has not yet started, it will stop immediately
858 * when it is actually started. <b>WARNING</b>This bypasses Java security,
859 * and can throw a checked exception which the call stack is unprepared to
860 * handle. Do not abuse this power.
862 * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
863 * leave data in bad states. Hence, there is a security check:
864 * <code>checkAccess(this)</code>, plus another one if the current thread
865 * is not this: <code>RuntimePermission("stopThread")</code>. If you must
866 * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
867 * ThreadDeath is the only exception which does not print a stack trace when
868 * the thread dies.
870 * @param t the Throwable to throw when the Thread dies
871 * @throws SecurityException if you cannot stop the Thread
872 * @throws NullPointerException in the calling thread, if t is null
873 * @see #interrupt()
874 * @see #checkAccess()
875 * @see #start()
876 * @see ThreadDeath
877 * @see ThreadGroup#uncaughtException(Thread, Throwable)
878 * @see SecurityManager#checkAccess(Thread)
879 * @see SecurityManager#checkPermission(Permission)
880 * @deprecated unsafe operation, try not to use
882 public final native void stop(Throwable t);
885 * Suspend this Thread. It will not come back, ever, unless it is resumed.
887 * <p>This is inherently unsafe, as the suspended thread still holds locks,
888 * and can potentially deadlock your program. Hence, there is a security
889 * check: <code>checkAccess</code>.
891 * @throws SecurityException if you cannot suspend the Thread
892 * @see #checkAccess()
893 * @see #resume()
894 * @deprecated unsafe operation, try not to use
896 public final native void suspend();
899 * Set this Thread's priority. There may be a security check,
900 * <code>checkAccess</code>, then the priority is set to the smaller of
901 * priority and the ThreadGroup maximum priority.
903 * @param priority the new priority for this Thread
904 * @throws IllegalArgumentException if priority exceeds MIN_PRIORITY or
905 * MAX_PRIORITY
906 * @throws SecurityException if you cannot modify this Thread
907 * @see #getPriority()
908 * @see #checkAccess()
909 * @see ThreadGroup#getMaxPriority()
910 * @see #MIN_PRIORITY
911 * @see #MAX_PRIORITY
913 public final native void setPriority(int newPriority);
916 * Returns a string representation of this thread, including the
917 * thread's name, priority, and thread group.
919 * @return a human-readable String representing this Thread
921 public String toString()
923 return ("Thread[" + name + "," + priority + ","
924 + (group == null ? "" : group.getName()) + "]");
927 private final native void initialize_native();
929 private final native static String gen_name();
932 * Returns the map used by ThreadLocal to store the thread local values.
934 static Map getThreadLocals()
936 Thread thread = currentThread();
937 Map locals = thread.locals;
938 if (locals == null)
940 locals = thread.locals = new WeakIdentityHashMap();
942 return locals;
945 /**
946 * Assigns the given <code>UncaughtExceptionHandler</code> to this
947 * thread. This will then be called if the thread terminates due
948 * to an uncaught exception, pre-empting that of the
949 * <code>ThreadGroup</code>.
951 * @param h the handler to use for this thread.
952 * @throws SecurityException if the current thread can't modify this thread.
953 * @since 1.5
955 public void setUncaughtExceptionHandler(UncaughtExceptionHandler h)
957 SecurityManager sm = SecurityManager.current; // Be thread-safe.
958 if (sm != null)
959 sm.checkAccess(this);
960 exceptionHandler = h;
963 /**
964 * <p>
965 * Returns the handler used when this thread terminates due to an
966 * uncaught exception. The handler used is determined by the following:
967 * </p>
968 * <ul>
969 * <li>If this thread has its own handler, this is returned.</li>
970 * <li>If not, then the handler of the thread's <code>ThreadGroup</code>
971 * object is returned.</li>
972 * <li>If both are unavailable, then <code>null</code> is returned
973 * (which can only happen when the thread was terminated since
974 * then it won't have an associated thread group anymore).</li>
975 * </ul>
977 * @return the appropriate <code>UncaughtExceptionHandler</code> or
978 * <code>null</code> if one can't be obtained.
979 * @since 1.5
981 public UncaughtExceptionHandler getUncaughtExceptionHandler()
983 return exceptionHandler != null ? exceptionHandler : group;
986 /**
987 * <p>
988 * Sets the default uncaught exception handler used when one isn't
989 * provided by the thread or its associated <code>ThreadGroup</code>.
990 * This exception handler is used when the thread itself does not
991 * have an exception handler, and the thread's <code>ThreadGroup</code>
992 * does not override this default mechanism with its own. As the group
993 * calls this handler by default, this exception handler should not defer
994 * to that of the group, as it may lead to infinite recursion.
995 * </p>
996 * <p>
997 * Uncaught exception handlers are used when a thread terminates due to
998 * an uncaught exception. Replacing this handler allows default code to
999 * be put in place for all threads in order to handle this eventuality.
1000 * </p>
1002 * @param h the new default uncaught exception handler to use.
1003 * @throws SecurityException if a security manager is present and
1004 * disallows the runtime permission
1005 * "setDefaultUncaughtExceptionHandler".
1006 * @since 1.5
1008 public static void
1009 setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler h)
1011 SecurityManager sm = SecurityManager.current; // Be thread-safe.
1012 if (sm != null)
1013 sm.checkPermission(new RuntimePermission("setDefaultUncaughtExceptionHandler"));
1014 defaultHandler = h;
1017 /**
1018 * Returns the handler used by default when a thread terminates
1019 * unexpectedly due to an exception, or <code>null</code> if one doesn't
1020 * exist.
1022 * @return the default uncaught exception handler.
1023 * @since 1.5
1025 public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
1027 return defaultHandler;
1031 * <p>
1032 * This interface is used to handle uncaught exceptions
1033 * which cause a <code>Thread</code> to terminate. When
1034 * a thread, t, is about to terminate due to an uncaught
1035 * exception, the virtual machine looks for a class which
1036 * implements this interface, in order to supply it with
1037 * the dying thread and its uncaught exception.
1038 * </p>
1039 * <p>
1040 * The virtual machine makes two attempts to find an
1041 * appropriate handler for the uncaught exception, in
1042 * the following order:
1043 * </p>
1044 * <ol>
1045 * <li>
1046 * <code>t.getUncaughtExceptionHandler()</code> --
1047 * the dying thread is queried first for a handler
1048 * specific to that thread.
1049 * </li>
1050 * <li>
1051 * <code>t.getThreadGroup()</code> --
1052 * the thread group of the dying thread is used to
1053 * handle the exception. If the thread group has
1054 * no special requirements for handling the exception,
1055 * it may simply forward it on to
1056 * <code>Thread.getDefaultUncaughtExceptionHandler()</code>,
1057 * the default handler, which is used as a last resort.
1058 * </li>
1059 * </ol>
1060 * <p>
1061 * The first handler found is the one used to handle
1062 * the uncaught exception.
1063 * </p>
1065 * @author Tom Tromey <tromey@redhat.com>
1066 * @author Andrew John Hughes <gnu_andrew@member.fsf.org>
1067 * @since 1.5
1068 * @see Thread#getUncaughtExceptionHandler()
1069 * @see Thread#setUncaughtExceptionHander(java.lang.Thread.UncaughtExceptionHandler)
1070 * @see Thread#getDefaultUncaughtExceptionHandler()
1071 * @see
1072 * Thread#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)
1074 public interface UncaughtExceptionHandler
1077 * Invoked by the virtual machine with the dying thread
1078 * and the uncaught exception. Any exceptions thrown
1079 * by this method are simply ignored by the virtual
1080 * machine.
1082 * @param thr the dying thread.
1083 * @param exc the uncaught exception.
1085 void uncaughtException(Thread thr, Throwable exc);