Mark as release
[official-gcc.git] / libjava / java / lang / Thread.java
blob2b7fb2aec0169757266a91f5f0083f7aafb62bfc
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 /** 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 /** The access control state for this thread. Package accessible
148 * for use by java.security.VMAccessControlState's native method.
150 Object accessControlState = null;
152 // This describes the top-most interpreter frame for this thread.
153 RawData interp_frame;
155 // Our native data - points to an instance of struct natThread.
156 private RawDataManaged data;
159 * Allocates a new <code>Thread</code> object. This constructor has
160 * the same effect as <code>Thread(null, null,</code>
161 * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
162 * a newly generated name. Automatically generated names are of the
163 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
164 * <p>
165 * Threads created this way must have overridden their
166 * <code>run()</code> method to actually do anything. An example
167 * illustrating this method being used follows:
168 * <p><blockquote><pre>
169 * import java.lang.*;
171 * class plain01 implements Runnable {
172 * String name;
173 * plain01() {
174 * name = null;
176 * plain01(String s) {
177 * name = s;
179 * public void run() {
180 * if (name == null)
181 * System.out.println("A new thread created");
182 * else
183 * System.out.println("A new thread with name " + name +
184 * " created");
187 * class threadtest01 {
188 * public static void main(String args[] ) {
189 * int failed = 0 ;
191 * <b>Thread t1 = new Thread();</b>
192 * if (t1 != null)
193 * System.out.println("new Thread() succeed");
194 * else {
195 * System.out.println("new Thread() failed");
196 * failed++;
200 * </pre></blockquote>
202 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
203 * java.lang.Runnable, java.lang.String)
205 public Thread()
207 this(null, null, gen_name());
211 * Allocates a new <code>Thread</code> object. This constructor has
212 * the same effect as <code>Thread(null, target,</code>
213 * <i>gname</i><code>)</code>, where <i>gname</i> is
214 * a newly generated name. Automatically generated names are of the
215 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
217 * @param target the object whose <code>run</code> method is called.
218 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
219 * java.lang.Runnable, java.lang.String)
221 public Thread(Runnable target)
223 this(null, target, gen_name());
227 * Allocates a new <code>Thread</code> object. This constructor has
228 * the same effect as <code>Thread(null, null, name)</code>.
230 * @param name the name of the new thread.
231 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
232 * java.lang.Runnable, java.lang.String)
234 public Thread(String name)
236 this(null, null, name);
240 * Allocates a new <code>Thread</code> object. This constructor has
241 * the same effect as <code>Thread(group, target,</code>
242 * <i>gname</i><code>)</code>, where <i>gname</i> is
243 * a newly generated name. Automatically generated names are of the
244 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
246 * @param group the group to put the Thread into
247 * @param target the Runnable object to execute
248 * @throws SecurityException if this thread cannot access <code>group</code>
249 * @throws IllegalThreadStateException if group is destroyed
250 * @see #Thread(ThreadGroup, Runnable, String)
252 public Thread(ThreadGroup group, Runnable target)
254 this(group, target, gen_name());
258 * Allocates a new <code>Thread</code> object. This constructor has
259 * the same effect as <code>Thread(group, null, name)</code>
261 * @param group the group to put the Thread into
262 * @param name the name for the Thread
263 * @throws NullPointerException if name is null
264 * @throws SecurityException if this thread cannot access <code>group</code>
265 * @throws IllegalThreadStateException if group is destroyed
266 * @see #Thread(ThreadGroup, Runnable, String)
268 public Thread(ThreadGroup group, String name)
270 this(group, null, name);
274 * Allocates a new <code>Thread</code> object. This constructor has
275 * the same effect as <code>Thread(null, target, name)</code>.
277 * @param target the Runnable object to execute
278 * @param name the name for the Thread
279 * @throws NullPointerException if name is null
280 * @see #Thread(ThreadGroup, Runnable, String)
282 public Thread(Runnable target, String name)
284 this(null, target, name);
288 * Allocate a new Thread object, with the specified ThreadGroup and name, and
289 * using the specified Runnable object's <code>run()</code> method to
290 * execute. If the Runnable object is null, <code>this</code> (which is
291 * a Runnable) is used instead.
293 * <p>If the ThreadGroup is null, the security manager is checked. If a
294 * manager exists and returns a non-null object for
295 * <code>getThreadGroup</code>, that group is used; otherwise the group
296 * of the creating thread is used. Note that the security manager calls
297 * <code>checkAccess</code> if the ThreadGroup is not null.
299 * <p>The new Thread will inherit its creator's priority and daemon status.
300 * These can be changed with <code>setPriority</code> and
301 * <code>setDaemon</code>.
303 * @param group the group to put the Thread into
304 * @param target the Runnable object to execute
305 * @param name the name for the Thread
306 * @throws NullPointerException if name is null
307 * @throws SecurityException if this thread cannot access <code>group</code>
308 * @throws IllegalThreadStateException if group is destroyed
309 * @see Runnable#run()
310 * @see #run()
311 * @see #setDaemon(boolean)
312 * @see #setPriority(int)
313 * @see SecurityManager#checkAccess(ThreadGroup)
314 * @see ThreadGroup#checkAccess()
316 public Thread(ThreadGroup group, Runnable target, String name)
318 this(currentThread(), group, target, name);
322 * Allocate a new Thread object, as if by
323 * <code>Thread(group, null, name)</code>, and give it the specified stack
324 * size, in bytes. The stack size is <b>highly platform independent</b>,
325 * and the virtual machine is free to round up or down, or ignore it
326 * completely. A higher value might let you go longer before a
327 * <code>StackOverflowError</code>, while a lower value might let you go
328 * longer before an <code>OutOfMemoryError</code>. Or, it may do absolutely
329 * nothing! So be careful, and expect to need to tune this value if your
330 * virtual machine even supports it.
332 * @param group the group to put the Thread into
333 * @param target the Runnable object to execute
334 * @param name the name for the Thread
335 * @param size the stack size, in bytes; 0 to be ignored
336 * @throws NullPointerException if name is null
337 * @throws SecurityException if this thread cannot access <code>group</code>
338 * @throws IllegalThreadStateException if group is destroyed
339 * @since 1.4
341 public Thread(ThreadGroup group, Runnable target, String name, long size)
343 // Just ignore stackSize for now.
344 this(currentThread(), group, target, name);
347 private Thread (Thread current, ThreadGroup g, Runnable r, String n)
349 // Make sure the current thread may create a new thread.
350 checkAccess();
352 // The Class Libraries book says ``threadName cannot be null''. I
353 // take this to mean NullPointerException.
354 if (n == null)
355 throw new NullPointerException ();
357 if (g == null)
359 // If CURRENT is null, then we are bootstrapping the first thread.
360 // Use ThreadGroup.root, the main threadgroup.
361 if (current == null)
362 group = ThreadGroup.root;
363 else
364 group = current.getThreadGroup();
366 else
367 group = g;
369 data = null;
370 interrupt_flag = false;
371 alive_flag = false;
372 startable_flag = true;
374 synchronized (Thread.class)
376 this.threadId = nextThreadId++;
379 if (current != null)
381 group.checkAccess();
383 daemon = current.isDaemon();
384 int gmax = group.getMaxPriority();
385 int pri = current.getPriority();
386 priority = (gmax < pri ? gmax : pri);
387 contextClassLoader = current.contextClassLoader;
388 InheritableThreadLocal.newChildThread(this);
390 else
392 daemon = false;
393 priority = NORM_PRIORITY;
396 name = n;
397 group.addThread(this);
398 runnable = r;
400 initialize_native ();
404 * Get the number of active threads in the current Thread's ThreadGroup.
405 * This implementation calls
406 * <code>currentThread().getThreadGroup().activeCount()</code>.
408 * @return the number of active threads in the current ThreadGroup
409 * @see ThreadGroup#activeCount()
411 public static int activeCount()
413 return currentThread().group.activeCount();
417 * Check whether the current Thread is allowed to modify this Thread. This
418 * passes the check on to <code>SecurityManager.checkAccess(this)</code>.
420 * @throws SecurityException if the current Thread cannot modify this Thread
421 * @see SecurityManager#checkAccess(Thread)
423 public final void checkAccess()
425 SecurityManager sm = System.getSecurityManager();
426 if (sm != null)
427 sm.checkAccess(this);
431 * Count the number of stack frames in this Thread. The Thread in question
432 * must be suspended when this occurs.
434 * @return the number of stack frames in this Thread
435 * @throws IllegalThreadStateException if this Thread is not suspended
436 * @deprecated pointless, since suspend is deprecated
438 public native int countStackFrames();
441 * Get the currently executing Thread.
443 * @return the currently executing Thread
445 public static native Thread currentThread();
448 * Originally intended to destroy this thread, this method was never
449 * implemented by Sun, and is hence a no-op.
451 public void destroy()
453 throw new NoSuchMethodError();
457 * Print a stack trace of the current thread to stderr using the same
458 * format as Throwable's printStackTrace() method.
460 * @see Throwable#printStackTrace()
462 public static void dumpStack()
464 (new Exception("Stack trace")).printStackTrace();
468 * Copy every active thread in the current Thread's ThreadGroup into the
469 * array. Extra threads are silently ignored. This implementation calls
470 * <code>getThreadGroup().enumerate(array)</code>, which may have a
471 * security check, <code>checkAccess(group)</code>.
473 * @param array the array to place the Threads into
474 * @return the number of Threads placed into the array
475 * @throws NullPointerException if array is null
476 * @throws SecurityException if you cannot access the ThreadGroup
477 * @see ThreadGroup#enumerate(Thread[])
478 * @see #activeCount()
479 * @see SecurityManager#checkAccess(ThreadGroup)
481 public static int enumerate(Thread[] array)
483 return currentThread().group.enumerate(array);
487 * Get this Thread's name.
489 * @return this Thread's name
491 public final String getName()
493 return name;
497 * Get this Thread's priority.
499 * @return the Thread's priority
501 public final int getPriority()
503 return priority;
507 * Get the ThreadGroup this Thread belongs to. If the thread has died, this
508 * returns null.
510 * @return this Thread's ThreadGroup
512 public final ThreadGroup getThreadGroup()
514 return group;
518 * Checks whether the current thread holds the monitor on a given object.
519 * This allows you to do <code>assert Thread.holdsLock(obj)</code>.
521 * @param obj the object to test lock ownership on.
522 * @return true if the current thread is currently synchronized on obj
523 * @throws NullPointerException if obj is null
524 * @since 1.4
526 public static native boolean holdsLock(Object obj);
529 * Interrupt this Thread. First, there is a security check,
530 * <code>checkAccess</code>. Then, depending on the current state of the
531 * thread, various actions take place:
533 * <p>If the thread is waiting because of {@link #wait()},
534 * {@link #sleep(long)}, or {@link #join()}, its <i>interrupt status</i>
535 * will be cleared, and an InterruptedException will be thrown. Notice that
536 * this case is only possible if an external thread called interrupt().
538 * <p>If the thread is blocked in an interruptible I/O operation, in
539 * {@link java.nio.channels.InterruptibleChannel}, the <i>interrupt
540 * status</i> will be set, and ClosedByInterruptException will be thrown.
542 * <p>If the thread is blocked on a {@link java.nio.channels.Selector}, the
543 * <i>interrupt status</i> will be set, and the selection will return, with
544 * a possible non-zero value, as though by the wakeup() method.
546 * <p>Otherwise, the interrupt status will be set.
548 * @throws SecurityException if you cannot modify this Thread
550 public native void interrupt();
553 * Determine whether the current Thread has been interrupted, and clear
554 * the <i>interrupted status</i> in the process.
556 * @return whether the current Thread has been interrupted
557 * @see #isInterrupted()
559 public static boolean interrupted()
561 return currentThread().isInterrupted(true);
565 * Determine whether the given Thread has been interrupted, but leave
566 * the <i>interrupted status</i> alone in the process.
568 * @return whether the Thread has been interrupted
569 * @see #interrupted()
571 public boolean isInterrupted()
573 return interrupt_flag;
577 * Determine whether this Thread is alive. A thread which is alive has
578 * started and not yet died.
580 * @return whether this Thread is alive
582 public final synchronized boolean isAlive()
584 return alive_flag;
588 * Tell whether this is a daemon Thread or not.
590 * @return whether this is a daemon Thread or not
591 * @see #setDaemon(boolean)
593 public final boolean isDaemon()
595 return daemon;
599 * Wait forever for the Thread in question to die.
601 * @throws InterruptedException if the Thread is interrupted; it's
602 * <i>interrupted status</i> will be cleared
604 public final void join() throws InterruptedException
606 join(0, 0);
610 * Wait the specified amount of time for the Thread in question to die.
612 * @param ms the number of milliseconds to wait, or 0 for forever
613 * @throws InterruptedException if the Thread is interrupted; it's
614 * <i>interrupted status</i> will be cleared
616 public final void join(long ms) throws InterruptedException
618 join(ms, 0);
622 * Wait the specified amount of time for the Thread in question to die.
624 * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
625 * not offer that fine a grain of timing resolution. Besides, there is
626 * no guarantee that this thread can start up immediately when time expires,
627 * because some other thread may be active. So don't expect real-time
628 * performance.
630 * @param ms the number of milliseconds to wait, or 0 for forever
631 * @param ns the number of extra nanoseconds to sleep (0-999999)
632 * @throws InterruptedException if the Thread is interrupted; it's
633 * <i>interrupted status</i> will be cleared
634 * @throws IllegalArgumentException if ns is invalid
635 * @XXX A ThreadListener would be nice, to make this efficient.
637 public final native void join(long ms, int ns)
638 throws InterruptedException;
641 * Resume a suspended thread.
643 * @throws SecurityException if you cannot resume the Thread
644 * @see #checkAccess()
645 * @see #suspend()
646 * @deprecated pointless, since suspend is deprecated
648 public final native void resume();
650 private final native void finish_();
653 * Determine whether the given Thread has been interrupted, but leave
654 * the <i>interrupted status</i> alone in the process.
656 * @return whether the current Thread has been interrupted
657 * @see #interrupted()
659 private boolean isInterrupted(boolean clear_flag)
661 boolean r = interrupt_flag;
662 if (clear_flag && r)
664 // Only clear the flag if we saw it as set. Otherwise this could
665 // potentially cause us to miss an interrupt in a race condition,
666 // because this method is not synchronized.
667 interrupt_flag = false;
669 return r;
673 * The method of Thread that will be run if there is no Runnable object
674 * associated with the Thread. Thread's implementation does nothing at all.
676 * @see #start()
677 * @see #Thread(ThreadGroup, Runnable, String)
679 public void run()
681 if (runnable != null)
682 runnable.run();
686 * Set the daemon status of this Thread. If this is a daemon Thread, then
687 * the VM may exit even if it is still running. This may only be called
688 * before the Thread starts running. There may be a security check,
689 * <code>checkAccess</code>.
691 * @param daemon whether this should be a daemon thread or not
692 * @throws SecurityException if you cannot modify this Thread
693 * @throws IllegalThreadStateException if the Thread is active
694 * @see #isDaemon()
695 * @see #checkAccess()
697 public final void setDaemon(boolean daemon)
699 if (!startable_flag)
700 throw new IllegalThreadStateException();
701 checkAccess();
702 this.daemon = daemon;
706 * Returns the context classloader of this Thread. The context
707 * classloader can be used by code that want to load classes depending
708 * on the current thread. Normally classes are loaded depending on
709 * the classloader of the current class. There may be a security check
710 * for <code>RuntimePermission("getClassLoader")</code> if the caller's
711 * class loader is not null or an ancestor of this thread's context class
712 * loader.
714 * @return the context class loader
715 * @throws SecurityException when permission is denied
716 * @see setContextClassLoader(ClassLoader)
717 * @since 1.2
719 public synchronized ClassLoader getContextClassLoader()
721 if (contextClassLoader == null)
722 contextClassLoader = ClassLoader.getSystemClassLoader();
724 SecurityManager sm = System.getSecurityManager();
725 // FIXME: we can't currently find the caller's class loader.
726 ClassLoader callers = null;
727 if (sm != null && callers != null)
729 // See if the caller's class loader is the same as or an
730 // ancestor of this thread's class loader.
731 while (callers != null && callers != contextClassLoader)
733 // FIXME: should use some internal version of getParent
734 // that avoids security checks.
735 callers = callers.getParent();
738 if (callers != contextClassLoader)
739 sm.checkPermission(new RuntimePermission("getClassLoader"));
742 return contextClassLoader;
746 * Sets the context classloader for this Thread. When not explicitly set,
747 * the context classloader for a thread is the same as the context
748 * classloader of the thread that created this thread. The first thread has
749 * as context classloader the system classloader. There may be a security
750 * check for <code>RuntimePermission("setContextClassLoader")</code>.
752 * @param classloader the new context class loader
753 * @throws SecurityException when permission is denied
754 * @see getContextClassLoader()
755 * @since 1.2
757 public synchronized void setContextClassLoader(ClassLoader classloader)
759 SecurityManager sm = System.getSecurityManager();
760 if (sm != null)
761 sm.checkPermission(new RuntimePermission("setContextClassLoader"));
762 this.contextClassLoader = classloader;
766 * Set this Thread's name. There may be a security check,
767 * <code>checkAccess</code>.
769 * @param name the new name for this Thread
770 * @throws NullPointerException if name is null
771 * @throws SecurityException if you cannot modify this Thread
773 public final void setName(String name)
775 checkAccess();
776 // The Class Libraries book says ``threadName cannot be null''. I
777 // take this to mean NullPointerException.
778 if (name == null)
779 throw new NullPointerException();
780 this.name = name;
784 * Causes the currently executing thread object to temporarily pause
785 * and allow other threads to execute.
787 public static native void yield();
790 * Suspend the current Thread's execution for the specified amount of
791 * time. The Thread will not lose any locks it has during this time. There
792 * are no guarantees which thread will be next to run, but most VMs will
793 * choose the highest priority thread that has been waiting longest.
795 * @param ms the number of milliseconds to sleep, or 0 for forever
796 * @throws InterruptedException if the Thread is interrupted; it's
797 * <i>interrupted status</i> will be cleared
798 * @see #notify()
799 * @see #wait(long)
801 public static void sleep(long ms) throws InterruptedException
803 sleep(ms, 0);
807 * Suspend the current Thread's execution for the specified amount of
808 * time. The Thread will not lose any locks it has during this time. There
809 * are no guarantees which thread will be next to run, but most VMs will
810 * choose the highest priority thread that has been waiting longest.
812 * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
813 * not offer that fine a grain of timing resolution. Besides, there is
814 * no guarantee that this thread can start up immediately when time expires,
815 * because some other thread may be active. So don't expect real-time
816 * performance.
818 * @param ms the number of milliseconds to sleep, or 0 for forever
819 * @param ns the number of extra nanoseconds to sleep (0-999999)
820 * @throws InterruptedException if the Thread is interrupted; it's
821 * <i>interrupted status</i> will be cleared
822 * @throws IllegalArgumentException if ns is invalid
823 * @see #notify()
824 * @see #wait(long, int)
826 public static native void sleep(long timeout, int nanos)
827 throws InterruptedException;
830 * Start this Thread, calling the run() method of the Runnable this Thread
831 * was created with, or else the run() method of the Thread itself. This
832 * is the only way to start a new thread; calling run by yourself will just
833 * stay in the same thread. The virtual machine will remove the thread from
834 * its thread group when the run() method completes.
836 * @throws IllegalThreadStateException if the thread has already started
837 * @see #run()
839 public native void start();
842 * Cause this Thread to stop abnormally because of the throw of a ThreadDeath
843 * error. If you stop a Thread that has not yet started, it will stop
844 * immediately when it is actually started.
846 * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
847 * leave data in bad states. Hence, there is a security check:
848 * <code>checkAccess(this)</code>, plus another one if the current thread
849 * is not this: <code>RuntimePermission("stopThread")</code>. If you must
850 * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
851 * ThreadDeath is the only exception which does not print a stack trace when
852 * the thread dies.
854 * @throws SecurityException if you cannot stop the Thread
855 * @see #interrupt()
856 * @see #checkAccess()
857 * @see #start()
858 * @see ThreadDeath
859 * @see ThreadGroup#uncaughtException(Thread, Throwable)
860 * @see SecurityManager#checkAccess(Thread)
861 * @see SecurityManager#checkPermission(Permission)
862 * @deprecated unsafe operation, try not to use
864 public final void stop()
866 // Argument doesn't matter, because this is no longer
867 // supported.
868 stop(null);
872 * Cause this Thread to stop abnormally and throw the specified exception.
873 * If you stop a Thread that has not yet started, it will stop immediately
874 * when it is actually started. <b>WARNING</b>This bypasses Java security,
875 * and can throw a checked exception which the call stack is unprepared to
876 * handle. Do not abuse this power.
878 * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
879 * leave data in bad states. Hence, there is a security check:
880 * <code>checkAccess(this)</code>, plus another one if the current thread
881 * is not this: <code>RuntimePermission("stopThread")</code>. If you must
882 * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
883 * ThreadDeath is the only exception which does not print a stack trace when
884 * the thread dies.
886 * @param t the Throwable to throw when the Thread dies
887 * @throws SecurityException if you cannot stop the Thread
888 * @throws NullPointerException in the calling thread, if t is null
889 * @see #interrupt()
890 * @see #checkAccess()
891 * @see #start()
892 * @see ThreadDeath
893 * @see ThreadGroup#uncaughtException(Thread, Throwable)
894 * @see SecurityManager#checkAccess(Thread)
895 * @see SecurityManager#checkPermission(Permission)
896 * @deprecated unsafe operation, try not to use
898 public final native void stop(Throwable t);
901 * Suspend this Thread. It will not come back, ever, unless it is resumed.
903 * <p>This is inherently unsafe, as the suspended thread still holds locks,
904 * and can potentially deadlock your program. Hence, there is a security
905 * check: <code>checkAccess</code>.
907 * @throws SecurityException if you cannot suspend the Thread
908 * @see #checkAccess()
909 * @see #resume()
910 * @deprecated unsafe operation, try not to use
912 public final native void suspend();
915 * Set this Thread's priority. There may be a security check,
916 * <code>checkAccess</code>, then the priority is set to the smaller of
917 * priority and the ThreadGroup maximum priority.
919 * @param priority the new priority for this Thread
920 * @throws IllegalArgumentException if priority exceeds MIN_PRIORITY or
921 * MAX_PRIORITY
922 * @throws SecurityException if you cannot modify this Thread
923 * @see #getPriority()
924 * @see #checkAccess()
925 * @see ThreadGroup#getMaxPriority()
926 * @see #MIN_PRIORITY
927 * @see #MAX_PRIORITY
929 public final native void setPriority(int newPriority);
932 * Returns a string representation of this thread, including the
933 * thread's name, priority, and thread group.
935 * @return a human-readable String representing this Thread
937 public String toString()
939 return ("Thread[" + name + "," + priority + ","
940 + (group == null ? "" : group.getName()) + "]");
943 private final native void initialize_native();
945 private final native static String gen_name();
948 * Returns the map used by ThreadLocal to store the thread local values.
950 static Map getThreadLocals()
952 Thread thread = currentThread();
953 Map locals = thread.locals;
954 if (locals == null)
956 locals = thread.locals = new WeakIdentityHashMap();
958 return locals;
961 /**
962 * Assigns the given <code>UncaughtExceptionHandler</code> to this
963 * thread. This will then be called if the thread terminates due
964 * to an uncaught exception, pre-empting that of the
965 * <code>ThreadGroup</code>.
967 * @param h the handler to use for this thread.
968 * @throws SecurityException if the current thread can't modify this thread.
969 * @since 1.5
971 public void setUncaughtExceptionHandler(UncaughtExceptionHandler h)
973 SecurityManager sm = SecurityManager.current; // Be thread-safe.
974 if (sm != null)
975 sm.checkAccess(this);
976 exceptionHandler = h;
979 /**
980 * <p>
981 * Returns the handler used when this thread terminates due to an
982 * uncaught exception. The handler used is determined by the following:
983 * </p>
984 * <ul>
985 * <li>If this thread has its own handler, this is returned.</li>
986 * <li>If not, then the handler of the thread's <code>ThreadGroup</code>
987 * object is returned.</li>
988 * <li>If both are unavailable, then <code>null</code> is returned
989 * (which can only happen when the thread was terminated since
990 * then it won't have an associated thread group anymore).</li>
991 * </ul>
993 * @return the appropriate <code>UncaughtExceptionHandler</code> or
994 * <code>null</code> if one can't be obtained.
995 * @since 1.5
997 public UncaughtExceptionHandler getUncaughtExceptionHandler()
999 return exceptionHandler != null ? exceptionHandler : group;
1002 /**
1003 * <p>
1004 * Sets the default uncaught exception handler used when one isn't
1005 * provided by the thread or its associated <code>ThreadGroup</code>.
1006 * This exception handler is used when the thread itself does not
1007 * have an exception handler, and the thread's <code>ThreadGroup</code>
1008 * does not override this default mechanism with its own. As the group
1009 * calls this handler by default, this exception handler should not defer
1010 * to that of the group, as it may lead to infinite recursion.
1011 * </p>
1012 * <p>
1013 * Uncaught exception handlers are used when a thread terminates due to
1014 * an uncaught exception. Replacing this handler allows default code to
1015 * be put in place for all threads in order to handle this eventuality.
1016 * </p>
1018 * @param h the new default uncaught exception handler to use.
1019 * @throws SecurityException if a security manager is present and
1020 * disallows the runtime permission
1021 * "setDefaultUncaughtExceptionHandler".
1022 * @since 1.5
1024 public static void
1025 setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler h)
1027 SecurityManager sm = SecurityManager.current; // Be thread-safe.
1028 if (sm != null)
1029 sm.checkPermission(new RuntimePermission("setDefaultUncaughtExceptionHandler"));
1030 defaultHandler = h;
1033 /**
1034 * Returns the handler used by default when a thread terminates
1035 * unexpectedly due to an exception, or <code>null</code> if one doesn't
1036 * exist.
1038 * @return the default uncaught exception handler.
1039 * @since 1.5
1041 public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
1043 return defaultHandler;
1046 /**
1047 * Returns the unique identifier for this thread. This ID is generated
1048 * on thread creation, and may be re-used on its death.
1050 * @return a positive long number representing the thread's ID.
1051 * @since 1.5
1053 public long getId()
1055 return threadId;
1059 * <p>
1060 * This interface is used to handle uncaught exceptions
1061 * which cause a <code>Thread</code> to terminate. When
1062 * a thread, t, is about to terminate due to an uncaught
1063 * exception, the virtual machine looks for a class which
1064 * implements this interface, in order to supply it with
1065 * the dying thread and its uncaught exception.
1066 * </p>
1067 * <p>
1068 * The virtual machine makes two attempts to find an
1069 * appropriate handler for the uncaught exception, in
1070 * the following order:
1071 * </p>
1072 * <ol>
1073 * <li>
1074 * <code>t.getUncaughtExceptionHandler()</code> --
1075 * the dying thread is queried first for a handler
1076 * specific to that thread.
1077 * </li>
1078 * <li>
1079 * <code>t.getThreadGroup()</code> --
1080 * the thread group of the dying thread is used to
1081 * handle the exception. If the thread group has
1082 * no special requirements for handling the exception,
1083 * it may simply forward it on to
1084 * <code>Thread.getDefaultUncaughtExceptionHandler()</code>,
1085 * the default handler, which is used as a last resort.
1086 * </li>
1087 * </ol>
1088 * <p>
1089 * The first handler found is the one used to handle
1090 * the uncaught exception.
1091 * </p>
1093 * @author Tom Tromey <tromey@redhat.com>
1094 * @author Andrew John Hughes <gnu_andrew@member.fsf.org>
1095 * @since 1.5
1096 * @see Thread#getUncaughtExceptionHandler()
1097 * @see Thread#setUncaughtExceptionHander(java.lang.Thread.UncaughtExceptionHandler)
1098 * @see Thread#getDefaultUncaughtExceptionHandler()
1099 * @see
1100 * Thread#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)
1102 public interface UncaughtExceptionHandler
1105 * Invoked by the virtual machine with the dying thread
1106 * and the uncaught exception. Any exceptions thrown
1107 * by this method are simply ignored by the virtual
1108 * machine.
1110 * @param thr the dying thread.
1111 * @param exc the uncaught exception.
1113 void uncaughtException(Thread thr, Throwable exc);
1117 * Returns the current state of the thread. This
1118 * is designed for monitoring thread behaviour, rather
1119 * than for synchronization control.
1121 * @return the current thread state.
1123 public String getState()
1125 // FIXME - Provide real implementation.
1126 return "NEW";