1 // Thread.java - Thread class.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
13 import gnu
.gcj
.RawData
;
15 /* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3
16 * "The Java Language Specification", ISBN 0-201-63451-1
17 * plus online API docs for JDK 1.2 beta from http://www.javasoft.com.
18 * Status: Believed complete to version 1.4, with caveats. We do not
19 * implement the deprecated (and dangerous) stop, suspend, and resume
20 * methods. Security implementation is not complete.
24 * Thread represents a single thread of execution in the VM. When an
25 * application VM starts up, it creates a non-daemon Thread which calls the
26 * main() method of a particular class. There may be other Threads running,
27 * such as the garbage collection thread.
29 * <p>Threads have names to identify them. These names are not necessarily
30 * unique. Every Thread has a priority, as well, which tells the VM which
31 * Threads should get more running time. New threads inherit the priority
32 * and daemon status of the parent thread, by default.
34 * <p>There are two methods of creating a Thread: you may subclass Thread and
35 * implement the <code>run()</code> method, at which point you may start the
36 * Thread by calling its <code>start()</code> method, or you may implement
37 * <code>Runnable</code> in the class you want to use and then call new
38 * <code>Thread(your_obj).start()</code>.
40 * <p>The virtual machine runs until all non-daemon threads have died (either
41 * by returning from the run() method as invoked by start(), or by throwing
42 * an uncaught exception); or until <code>System.exit</code> is called with
43 * adequate permissions.
45 * <p>It is unclear at what point a Thread should be added to a ThreadGroup,
46 * and at what point it should be removed. Should it be inserted when it
47 * starts, or when it is created? Should it be removed when it is suspended
48 * or interrupted? The only thing that is clear is that the Thread should be
49 * removed when it is stopped.
53 * @author Eric Blake <ebb9@email.byu.edu>
55 * @see Runtime#exit(int)
60 * @status updated to 1.4
62 public class Thread
implements Runnable
64 /** The maximum priority for a Thread. */
65 public final static int MAX_PRIORITY
= 10;
67 /** The minimum priority for a Thread. */
68 public final static int MIN_PRIORITY
= 1;
70 /** The priority a Thread gets by default. */
71 public final static int NORM_PRIORITY
= 5;
74 * Get the number of active threads in the current Thread's ThreadGroup.
75 * This implementation calls
76 * <code>currentThread().getThreadGroup().activeCount()</code>.
78 * @return the number of active threads in the current ThreadGroup
79 * @see ThreadGroup#activeCount()
81 public static int activeCount ()
83 return currentThread().getThreadGroup().activeCount();
87 * Check whether the current Thread is allowed to modify this Thread. This
88 * passes the check on to <code>SecurityManager.checkAccess(this)</code>.
90 * @throws SecurityException if the current Thread cannot modify this Thread
91 * @see SecurityManager#checkAccess(Thread)
93 public final void checkAccess ()
95 SecurityManager s
= System
.getSecurityManager();
101 * Count the number of stack frames in this Thread. The Thread in question
102 * must be suspended when this occurs.
104 * @return the number of stack frames in this Thread
105 * @throws IllegalThreadStateException if this Thread is not suspended
106 * @deprecated pointless, since suspend is deprecated
108 public native int countStackFrames ();
111 * Get the currently executing Thread.
113 * @return the currently executing Thread
115 public static native Thread
currentThread ();
118 * Originally intended to destroy this thread, this method was never
119 * implemented by Sun, and is hence a no-op.
121 public native void destroy ();
124 * Print a stack trace of the current thread to stderr using the same
125 * format as Throwable's printStackTrace() method.
127 * @see Throwable#printStackTrace()
129 public static void dumpStack ()
131 (new Exception ("Stack trace")).printStackTrace ();
135 * Copy every active thread in the current Thread's ThreadGroup into the
136 * array. Extra threads are silently ignored. This implementation calls
137 * <code>getThreadGroup().enumerate(array)</code>, which may have a
138 * security check, <code>checkAccess(group)</code>.
140 * @param array the array to place the Threads into
141 * @return the number of Threads placed into the array
142 * @throws NullPointerException if array is null
143 * @throws SecurityException if you cannot access the ThreadGroup
144 * @see ThreadGroup#enumerate(Thread[])
145 * @see #activeCount()
146 * @see SecurityManager#checkAccess(ThreadGroup)
148 public static int enumerate (Thread
[] threads
)
150 return currentThread().group
.enumerate(threads
);
154 * Get this Thread's name.
156 * @return this Thread's name
158 public final String
getName ()
164 * Get this Thread's priority.
166 * @return the Thread's priority
168 public final int getPriority ()
174 * Get the ThreadGroup this Thread belongs to. If the thread has died, this
177 * @return this Thread's ThreadGroup
179 public final ThreadGroup
getThreadGroup ()
185 * Return true if this Thread holds the object's lock, false otherwise.
187 * @param obj the object to test lock ownership on.
188 * @throws NullPointerException if obj is null.
191 public static native boolean holdsLock (Object obj
);
194 * Interrupt this Thread. First, there is a security check,
195 * <code>checkAccess</code>. Then, depending on the current state of the
196 * thread, various actions take place:
198 * <p>If the thread is waiting because of {@link #wait()},
199 * {@link #sleep(long)}, or {@link #join()}, its <i>interrupt status</i>
200 * will be cleared, and an InterruptedException will be thrown. Notice that
201 * this case is only possible if an external thread called interrupt().
203 * <p>If the thread is blocked in an interruptible I/O operation, in
204 * {@link java.nio.channels.InterruptibleChannel}, the <i>interrupt
205 * status</i> will be set, and ClosedByInterruptException will be thrown.
207 * <p>If the thread is blocked on a {@link java.nio.channels.Selector}, the
208 * <i>interrupt status</i> will be set, and the selection will return, with
209 * a possible non-zero value, as though by the wakeup() method.
211 * <p>Otherwise, the interrupt status will be set.
213 * @throws SecurityException if you cannot modify this Thread
215 public native void interrupt ();
218 * Determine whether the current Thread has been interrupted, and clear
219 * the <i>interrupted status</i> in the process.
221 * @return whether the current Thread has been interrupted
222 * @see #isInterrupted()
224 public static boolean interrupted ()
226 return currentThread().isInterrupted (true);
230 * Determine whether the given Thread has been interrupted, but leave
231 * the <i>interrupted status</i> alone in the process.
233 * @return whether the current Thread has been interrupted
234 * @see #interrupted()
236 public boolean isInterrupted ()
238 return interrupt_flag
;
242 * Determine whether this Thread is alive. A thread which is alive has
243 * started and not yet died.
245 * @return whether this Thread is alive
247 public final boolean isAlive ()
253 * Tell whether this is a daemon Thread or not.
255 * @return whether this is a daemon Thread or not
256 * @see #setDaemon(boolean)
258 public final boolean isDaemon ()
264 * Wait forever for the Thread in question to die.
266 * @throws InterruptedException if the Thread is interrupted; it's
267 * <i>interrupted status</i> will be cleared
269 public final void join () throws InterruptedException
275 * Wait the specified amount of time for the Thread in question to die.
277 * @param ms the number of milliseconds to wait, or 0 for forever
278 * @throws InterruptedException if the Thread is interrupted; it's
279 * <i>interrupted status</i> will be cleared
281 public final void join (long timeout
) throws InterruptedException
287 * Wait the specified amount of time for the Thread in question to die.
289 * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
290 * not offer that fine a grain of timing resolution. Besides, there is
291 * no guarantee that this thread can start up immediately when time expires,
292 * because some other thread may be active. So don't expect real-time
295 * @param ms the number of milliseconds to wait, or 0 for forever
296 * @param ns the number of extra nanoseconds to sleep (0-999999)
297 * @throws InterruptedException if the Thread is interrupted; it's
298 * <i>interrupted status</i> will be cleared
299 * @throws IllegalArgumentException if ns is invalid
300 * @XXX A ThreadListener would be nice, to make this efficient.
302 public final native void join (long timeout
, int nanos
)
303 throws InterruptedException
;
306 * Resume a suspended thread.
309 * @deprecated pointless, since suspend is deprecated
311 public final native void resume ();
313 private final native void finish_ ();
316 * Determine whether the given Thread has been interrupted, but leave
317 * the <i>interrupted status</i> alone in the process.
319 * @return whether the current Thread has been interrupted
320 * @see #interrupted()
322 private boolean isInterrupted (boolean clear_flag
)
324 boolean r
= interrupt_flag
;
327 // Only clear the flag if we saw it as set. Otherwise this could
328 // potentially cause us to miss an interrupt in a race condition,
329 // because this method is not synchronized.
330 interrupt_flag
= false;
336 * The method of Thread that will be run if there is no Runnable object
337 * associated with the Thread. Thread's implementation does nothing at all.
340 * @see #Thread(ThreadGroup, Runnable, String)
344 if (runnable
!= null)
349 * Set the daemon status of this Thread. If this is a daemon Thread, then
350 * the VM may exit even if it is still running. This may only be called
351 * before the Thread starts running. There may be a security check,
352 * <code>checkAccess</code>.
354 * @param daemon whether this should be a daemon thread or not
355 * @throws SecurityException if you cannot modify this Thread
356 * @throws IllegalThreadStateException if the Thread is active
358 * @see #checkAccess()
360 public final void setDaemon (boolean status
)
364 throw new IllegalThreadStateException ();
365 daemon_flag
= status
;
369 * Returns the context classloader of this Thread. The context
370 * classloader can be used by code that want to load classes depending
371 * on the current thread. Normally classes are loaded depending on
372 * the classloader of the current class. There may be a security check
373 * for <code>RuntimePermission("getClassLoader")</code> if the caller's
374 * class loader is not null or an ancestor of this thread's context class
377 * @return the context class loader
378 * @throws SecurityException when permission is denied
379 * @see setContextClassLoader(ClassLoader)
382 public synchronized ClassLoader
getContextClassLoader()
384 if (context_class_loader
== null)
385 context_class_loader
= ClassLoader
.getSystemClassLoader ();
387 SecurityManager s
= System
.getSecurityManager();
388 // FIXME: we can't currently find the caller's class loader.
389 ClassLoader callers
= null;
390 if (s
!= null && callers
!= null)
392 // See if the caller's class loader is the same as or an
393 // ancestor of this thread's class loader.
394 while (callers
!= null && callers
!= context_class_loader
)
396 // FIXME: should use some internal version of getParent
397 // that avoids security checks.
398 callers
= callers
.getParent ();
401 if (callers
!= context_class_loader
)
402 s
.checkPermission (new RuntimePermission ("getClassLoader"));
405 return context_class_loader
;
409 * Returns the context classloader of this Thread. The context
410 * classloader can be used by code that want to load classes depending
411 * on the current thread. Normally classes are loaded depending on
412 * the classloader of the current class. There may be a security check
413 * for <code>RuntimePermission("getClassLoader")</code> if the caller's
414 * class loader is not null or an ancestor of this thread's context class
417 * @return the context class loader
418 * @throws SecurityException when permission is denied
419 * @see setContextClassLoader(ClassLoader)
422 public synchronized void setContextClassLoader(ClassLoader cl
)
424 SecurityManager s
= System
.getSecurityManager ();
426 s
.checkPermission (new RuntimePermission ("setContextClassLoader"));
427 context_class_loader
= cl
;
431 * Set this Thread's name. There may be a security check,
432 * <code>checkAccess</code>.
434 * @param name the new name for this Thread
435 * @throws NullPointerException if name is null
436 * @throws SecurityException if you cannot modify this Thread
438 public final void setName (String n
)
441 // The Class Libraries book says ``threadName cannot be null''. I
442 // take this to mean NullPointerException.
444 throw new NullPointerException ();
449 * Set this Thread's priority. There may be a security check,
450 * <code>checkAccess</code>, then the priority is set to the smaller of
451 * priority and the ThreadGroup maximum priority.
453 * @param priority the new priority for this Thread
454 * @throws IllegalArgumentException if priority exceeds MIN_PRIORITY or
456 * @throws SecurityException if you cannot modify this Thread
457 * @see #getPriority()
458 * @see #checkAccess()
459 * @see ThreadGroup#getMaxPriority()
463 public final native void setPriority (int newPriority
);
466 * Suspend the current Thread's execution for the specified amount of
467 * time. The Thread will not lose any locks it has during this time. There
468 * are no guarantees which thread will be next to run, but most VMs will
469 * choose the highest priority thread that has been waiting longest.
471 * @param ms the number of milliseconds to sleep, or 0 for forever
472 * @throws InterruptedException if the Thread is interrupted; it's
473 * <i>interrupted status</i> will be cleared
477 public static void sleep (long timeout
) throws InterruptedException
483 * Suspend the current Thread's execution for the specified amount of
484 * time. The Thread will not lose any locks it has during this time. There
485 * are no guarantees which thread will be next to run, but most VMs will
486 * choose the highest priority thread that has been waiting longest.
488 * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
489 * not offer that fine a grain of timing resolution. Besides, there is
490 * no guarantee that this thread can start up immediately when time expires,
491 * because some other thread may be active. So don't expect real-time
494 * @param ms the number of milliseconds to sleep, or 0 for forever
495 * @param ns the number of extra nanoseconds to sleep (0-999999)
496 * @throws InterruptedException if the Thread is interrupted; it's
497 * <i>interrupted status</i> will be cleared
498 * @throws IllegalArgumentException if ns is invalid
500 * @see #wait(long, int)
502 public static native void sleep (long timeout
, int nanos
)
503 throws InterruptedException
;
506 * Start this Thread, calling the run() method of the Runnable this Thread
507 * was created with, or else the run() method of the Thread itself. This
508 * is the only way to start a new thread; calling run by yourself will just
509 * stay in the same thread. The virtual machine will remove the thread from
510 * its thread group when the run() method completes.
512 * @throws IllegalThreadStateException if the thread has already started
515 public native void start ();
518 * Cause this Thread to stop abnormally because of the throw of a ThreadDeath
519 * error. If you stop a Thread that has not yet started, it will stop
520 * immediately when it is actually started.
522 * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
523 * leave data in bad states. Hence, there is a security check:
524 * <code>checkAccess(this)</code>, plus another one if the current thread
525 * is not this: <code>RuntimePermission("stopThread")</code>. If you must
526 * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
527 * ThreadDeath is the only exception which does not print a stack trace when
530 * @throws SecurityException if you cannot stop the Thread
532 * @see #checkAccess()
535 * @see ThreadGroup#uncaughtException(Thread, Throwable)
536 * @see SecurityManager#checkAccess(Thread)
537 * @see SecurityManager#checkPermission(Permission)
538 * @deprecated unsafe operation, try not to use
540 public final void stop ()
542 // Argument doesn't matter, because this is no longer
548 * Cause this Thread to stop abnormally and throw the specified exception.
549 * If you stop a Thread that has not yet started, it will stop immediately
550 * when it is actually started. <b>WARNING</b>This bypasses Java security,
551 * and can throw a checked exception which the call stack is unprepared to
552 * handle. Do not abuse this power.
554 * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
555 * leave data in bad states. Hence, there is a security check:
556 * <code>checkAccess(this)</code>, plus another one if the current thread
557 * is not this: <code>RuntimePermission("stopThread")</code>. If you must
558 * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
559 * ThreadDeath is the only exception which does not print a stack trace when
562 * @param t the Throwable to throw when the Thread dies
563 * @throws SecurityException if you cannot stop the Thread
564 * @throws NullPointerException in the calling thread, if t is null
566 * @see #checkAccess()
569 * @see ThreadGroup#uncaughtException(Thread, Throwable)
570 * @see SecurityManager#checkAccess(Thread)
571 * @see SecurityManager#checkPermission(Permission)
572 * @deprecated unsafe operation, try not to use
574 public final native void stop (Throwable e
);
577 * Suspend this Thread. It will not come back, ever, unless it is resumed.
579 * <p>This is inherently unsafe, as the suspended thread still holds locks,
580 * and can potentially deadlock your program. Hence, there is a security
581 * check: <code>checkAccess</code>.
583 * @throws SecurityException if you cannot suspend the Thread
584 * @see #checkAccess()
586 * @deprecated unsafe operation, try not to use
588 public final native void suspend ();
590 private final native void initialize_native ();
592 private final native static String
gen_name ();
595 * Allocate a new Thread object, with the specified ThreadGroup and name, and
596 * using the specified Runnable object's <code>run()</code> method to
597 * execute. If the Runnable object is null, <code>this</code> (which is
598 * a Runnable) is used instead.
600 * <p>If the ThreadGroup is null, the security manager is checked. If a
601 * manager exists and returns a non-null object for
602 * <code>getThreadGroup</code>, that group is used; otherwise the group
603 * of the creating thread is used. Note that the security manager calls
604 * <code>checkAccess</code> if the ThreadGroup is not null.
606 * <p>The new Thread will inherit its creator's priority and daemon status.
607 * These can be changed with <code>setPriority</code> and
608 * <code>setDaemon</code>.
610 * @param group the group to put the Thread into
611 * @param target the Runnable object to execute
612 * @param name the name for the Thread
613 * @throws NullPointerException if name is null
614 * @throws SecurityException if this thread cannot access <code>group</code>
615 * @throws IllegalThreadStateException if group is destroyed
616 * @see Runnable#run()
618 * @see #setDaemon(boolean)
619 * @see #setPriority(int)
620 * @see SecurityManager#checkAccess(ThreadGroup)
621 * @see ThreadGroup#checkAccess()
623 public Thread (ThreadGroup g
, Runnable r
, String n
)
625 this (currentThread (), g
, r
, n
);
629 * Allocate a new Thread object, as if by
630 * <code>Thread(group, null, name)</code>, and give it the specified stack
631 * size, in bytes. The stack size is <b>highly platform independent</b>,
632 * and the virtual machine is free to round up or down, or ignore it
633 * completely. A higher value might let you go longer before a
634 * <code>StackOverflowError</code>, while a lower value might let you go
635 * longer before an <code>OutOfMemoryError</code>. Or, it may do absolutely
636 * nothing! So be careful, and expect to need to tune this value if your
637 * virtual machine even supports it.
639 * @param group the group to put the Thread into
640 * @param target the Runnable object to execute
641 * @param name the name for the Thread
642 * @param size the stack size, in bytes; 0 to be ignored
643 * @throws NullPointerException if name is null
644 * @throws SecurityException if this thread cannot access <code>group</code>
645 * @throws IllegalThreadStateException if group is destroyed
648 public Thread (ThreadGroup g
, Runnable r
, String n
, long size
)
650 // Just ignore stackSize for now.
651 this (currentThread (), g
, r
, n
);
654 private Thread (Thread current
, ThreadGroup g
, Runnable r
, String n
)
656 // The Class Libraries book says ``threadName cannot be null''. I
657 // take this to mean NullPointerException.
659 throw new NullPointerException ();
663 // If CURRENT is null, then we are bootstrapping the first thread.
664 // Use ThreadGroup.root, the main threadgroup.
666 group
= ThreadGroup
.root
;
668 group
= current
.getThreadGroup();
674 interrupt_flag
= false;
676 startable_flag
= true;
682 daemon_flag
= current
.isDaemon();
683 int gmax
= group
.getMaxPriority();
684 int pri
= current
.getPriority();
685 priority
= (gmax
< pri ? gmax
: pri
);
686 context_class_loader
= current
.context_class_loader
;
687 InheritableThreadLocal
.newChildThread(this);
692 priority
= NORM_PRIORITY
;
696 group
.addThread(this);
699 initialize_native ();
703 * Allocates a new <code>Thread</code> object. This constructor has
704 * the same effect as <code>Thread(null, null,</code>
705 * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
706 * a newly generated name. Automatically generated names are of the
707 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
709 * Threads created this way must have overridden their
710 * <code>run()</code> method to actually do anything. An example
711 * illustrating this method being used follows:
712 * <p><blockquote><pre>
713 * import java.lang.*;
715 * class plain01 implements Runnable {
720 * plain01(String s) {
723 * public void run() {
725 * System.out.println("A new thread created");
727 * System.out.println("A new thread with name " + name +
731 * class threadtest01 {
732 * public static void main(String args[] ) {
735 * <b>Thread t1 = new Thread();</b>
737 * System.out.println("new Thread() succeed");
739 * System.out.println("new Thread() failed");
744 * </pre></blockquote>
746 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
747 * java.lang.Runnable, java.lang.String)
751 this (null, null, gen_name ());
755 * Allocates a new <code>Thread</code> object. This constructor has
756 * the same effect as <code>Thread(null, target,</code>
757 * <i>gname</i><code>)</code>, where <i>gname</i> is
758 * a newly generated name. Automatically generated names are of the
759 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
761 * @param target the object whose <code>run</code> method is called.
762 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
763 * java.lang.Runnable, java.lang.String)
765 public Thread (Runnable r
)
767 this (null, r
, gen_name ());
771 * Allocates a new <code>Thread</code> object. This constructor has
772 * the same effect as <code>Thread(null, null, name)</code>.
774 * @param name the name of the new thread.
775 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
776 * java.lang.Runnable, java.lang.String)
778 public Thread (String n
)
780 this (null, null, n
);
784 * Allocates a new <code>Thread</code> object. This constructor has
785 * the same effect as <code>Thread(group, target,</code>
786 * <i>gname</i><code>)</code>, where <i>gname</i> is
787 * a newly generated name. Automatically generated names are of the
788 * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
790 * @param group the thread group.
791 * @param target the object whose <code>run</code> method is called.
792 * @exception SecurityException if the current thread cannot create a
793 * thread in the specified thread group.
794 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
795 * java.lang.Runnable, java.lang.String)
797 public Thread (ThreadGroup g
, Runnable r
)
799 this (g
, r
, gen_name ());
803 * Allocates a new <code>Thread</code> object. This constructor has
804 * the same effect as <code>Thread(group, null, name)</code>
806 * @param group the thread group.
807 * @param name the name of the new thread.
808 * @exception SecurityException if the current thread cannot create a
809 * thread in the specified thread group.
810 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
811 * java.lang.Runnable, java.lang.String)
813 public Thread (ThreadGroup g
, String n
)
819 * Allocates a new <code>Thread</code> object. This constructor has
820 * the same effect as <code>Thread(null, target, name)</code>.
822 * @param target the object whose <code>run</code> method is called.
823 * @param name the name of the new thread.
824 * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
825 * java.lang.Runnable, java.lang.String)
827 public Thread (Runnable r
, String n
)
833 * Returns a string representation of this thread, including the
834 * thread's name, priority, and thread group.
836 * @return a string representation of this thread.
838 public String
toString ()
840 return "Thread[" + name
+ "," + priority
+ "," +
841 (group
== null ?
"" : group
.getName()) + "]";
845 * Causes the currently executing thread object to temporarily pause
846 * and allow other threads to execute.
848 public static native void yield ();
853 private Runnable runnable
;
854 private int priority
;
855 private boolean daemon_flag
;
856 boolean interrupt_flag
;
857 private boolean alive_flag
;
858 private boolean startable_flag
;
859 private ClassLoader context_class_loader
;
861 // This describes the top-most interpreter frame for this thread.
862 RawData interp_frame
;
864 // Our native data - points to an instance of struct natThread.