001/* Thread -- an independent thread of executable code
002   Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
003   Free Software Foundation
004
005This file is part of GNU Classpath.
006
007GNU Classpath is free software; you can redistribute it and/or modify
008it under the terms of the GNU General Public License as published by
009the Free Software Foundation; either version 2, or (at your option)
010any later version.
011
012GNU Classpath is distributed in the hope that it will be useful, but
013WITHOUT ANY WARRANTY; without even the implied warranty of
014MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
015General Public License for more details.
016
017You should have received a copy of the GNU General Public License
018along with GNU Classpath; see the file COPYING.  If not, write to the
019Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02002110-1301 USA.
021
022Linking this library statically or dynamically with other modules is
023making a combined work based on this library.  Thus, the terms and
024conditions of the GNU General Public License cover the whole
025combination.
026
027As a special exception, the copyright holders of this library give you
028permission to link this library with independent modules to produce an
029executable, regardless of the license terms of these independent
030modules, and to copy and distribute the resulting executable under
031terms of your choice, provided that you also meet, for each linked
032independent module, the terms and conditions of the license of that
033module.  An independent module is a module which is not derived from
034or based on this library.  If you modify this library, you may extend
035this exception to your version of the library, but you are not
036obligated to do so.  If you do not wish to do so, delete this
037exception statement from your version. */
038
039package java.lang;
040
041import gnu.classpath.VMStackWalker;
042import gnu.gcj.RawData;
043import gnu.gcj.RawDataManaged;
044import gnu.java.util.WeakIdentityHashMap;
045
046import java.lang.management.ManagementFactory;
047import java.lang.management.ThreadInfo;
048import java.lang.management.ThreadMXBean;
049
050import java.util.HashMap;
051import java.util.Map;
052
053import java.lang.reflect.InvocationTargetException;
054import java.lang.reflect.Method;
055
056/* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3
057 * "The Java Language Specification", ISBN 0-201-63451-1
058 * plus online API docs for JDK 1.2 beta from http://www.javasoft.com.
059 * Status:  Believed complete to version 1.4, with caveats. We do not
060 *          implement the deprecated (and dangerous) stop, suspend, and resume
061 *          methods. Security implementation is not complete.
062 */
063
064/**
065 * Thread represents a single thread of execution in the VM. When an
066 * application VM starts up, it creates a non-daemon Thread which calls the
067 * main() method of a particular class.  There may be other Threads running,
068 * such as the garbage collection thread.
069 *
070 * <p>Threads have names to identify them.  These names are not necessarily
071 * unique. Every Thread has a priority, as well, which tells the VM which
072 * Threads should get more running time. New threads inherit the priority
073 * and daemon status of the parent thread, by default.
074 *
075 * <p>There are two methods of creating a Thread: you may subclass Thread and
076 * implement the <code>run()</code> method, at which point you may start the
077 * Thread by calling its <code>start()</code> method, or you may implement
078 * <code>Runnable</code> in the class you want to use and then call new
079 * <code>Thread(your_obj).start()</code>.
080 *
081 * <p>The virtual machine runs until all non-daemon threads have died (either
082 * by returning from the run() method as invoked by start(), or by throwing
083 * an uncaught exception); or until <code>System.exit</code> is called with
084 * adequate permissions.
085 *
086 * <p>It is unclear at what point a Thread should be added to a ThreadGroup,
087 * and at what point it should be removed. Should it be inserted when it
088 * starts, or when it is created?  Should it be removed when it is suspended
089 * or interrupted?  The only thing that is clear is that the Thread should be
090 * removed when it is stopped.
091 *
092 * @author Tom Tromey
093 * @author John Keiser
094 * @author Eric Blake (ebb9@email.byu.edu)
095 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
096 * @see Runnable
097 * @see Runtime#exit(int)
098 * @see #run()
099 * @see #start()
100 * @see ThreadLocal
101 * @since 1.0
102 * @status updated to 1.4
103 */
104public class Thread implements Runnable
105{
106  /** The minimum priority for a Thread. */
107  public static final int MIN_PRIORITY = 1;
108
109  /** The priority a Thread gets by default. */
110  public static final int NORM_PRIORITY = 5;
111
112  /** The maximum priority for a Thread. */
113  public static final int MAX_PRIORITY = 10;
114
115  /**
116   * The group this thread belongs to. This is set to null by
117   * ThreadGroup.removeThread when the thread dies.
118   */
119  ThreadGroup group;
120
121  /** The object to run(), null if this is the target. */
122  private Runnable runnable;
123
124  /** The thread name, non-null. */
125  String name;
126
127  /** Whether the thread is a daemon. */
128  private boolean daemon;
129
130  /** The thread priority, 1 to 10. */
131  private int priority;
132
133  boolean interrupt_flag;
134
135  /** A thread is either alive, dead, or being sent a signal; if it is
136      being sent a signal, it is also alive.  Thus, if you want to
137      know if a thread is alive, it is sufficient to test 
138      alive_status != THREAD_DEAD. */
139  private static final byte THREAD_DEAD = 0;
140  private static final byte THREAD_ALIVE = 1;
141  private static final byte THREAD_SIGNALED = 2;
142
143  private boolean startable_flag;
144
145  /** The context classloader for this Thread. */
146  private ClassLoader contextClassLoader;
147
148  /** This thread's ID.  */
149  private final long threadId;
150
151  /** The next thread ID to use.  */
152  private static long nextThreadId;
153
154  /** Used to generate the next thread ID to use.  */
155  private static long totalThreadsCreated;
156
157  /** The default exception handler.  */
158  private static UncaughtExceptionHandler defaultHandler;
159
160  /** Thread local storage. Package accessible for use by
161    * InheritableThreadLocal.
162    */
163  ThreadLocalMap locals;
164
165  /** The uncaught exception handler.  */
166  UncaughtExceptionHandler exceptionHandler;
167
168  /** This object is recorded while the thread is blocked to permit
169   * monitoring and diagnostic tools to identify the reasons that
170   * threads are blocked.
171   */
172  private Object parkBlocker;
173
174  /** Used by Unsafe.park and Unsafe.unpark.  Se Unsafe for a full
175      description.  */
176  static final byte THREAD_PARK_RUNNING = 0;
177  static final byte THREAD_PARK_PERMIT = 1;
178  static final byte THREAD_PARK_PARKED = 2;
179  static final byte THREAD_PARK_DEAD = 3;
180
181  /** The access control state for this thread.  Package accessible
182    * for use by java.security.VMAccessControlState's native method.
183    */
184  Object accessControlState = null;
185  
186  // This describes the top-most interpreter frame for this thread.
187  RawData interp_frame;
188  
189  // This describes the top most frame in the composite (interp + JNI) stack
190  RawData frame;
191
192  // Current state.
193  volatile int state;
194
195  // Our native data - points to an instance of struct natThread.
196  RawDataManaged data;
197
198  /**
199   * Allocates a new <code>Thread</code> object. This constructor has
200   * the same effect as <code>Thread(null, null,</code>
201   * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
202   * a newly generated name. Automatically generated names are of the
203   * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
204   * <p>
205   * Threads created this way must have overridden their
206   * <code>run()</code> method to actually do anything.  An example
207   * illustrating this method being used follows:
208   * <p><blockquote><pre>
209   *     import java.lang.*;
210   *
211   *     class plain01 implements Runnable {
212   *         String name;
213   *         plain01() {
214   *             name = null;
215   *         }
216   *         plain01(String s) {
217   *             name = s;
218   *         }
219   *         public void run() {
220   *             if (name == null)
221   *                 System.out.println("A new thread created");
222   *             else
223   *                 System.out.println("A new thread with name " + name +
224   *                                    " created");
225   *         }
226   *     }
227   *     class threadtest01 {
228   *         public static void main(String args[] ) {
229   *             int failed = 0 ;
230   *
231   *             <b>Thread t1 = new Thread();</b>
232   *             if (t1 != null)
233   *                 System.out.println("new Thread() succeed");
234   *             else {
235   *                 System.out.println("new Thread() failed");
236   *                 failed++;
237   *             }
238   *         }
239   *     }
240   * </pre></blockquote>
241   *
242   * @see     java.lang.Thread#Thread(java.lang.ThreadGroup,
243   *          java.lang.Runnable, java.lang.String)
244   */
245  public Thread()
246  {
247    this(null, null, gen_name());
248  }
249
250  /**
251   * Allocates a new <code>Thread</code> object. This constructor has
252   * the same effect as <code>Thread(null, target,</code>
253   * <i>gname</i><code>)</code>, where <i>gname</i> is
254   * a newly generated name. Automatically generated names are of the
255   * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
256   *
257   * @param target the object whose <code>run</code> method is called.
258   * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
259   *                              java.lang.Runnable, java.lang.String)
260   */
261  public Thread(Runnable target)
262  {
263    this(null, target, gen_name());
264  }
265
266  /**
267   * Allocates a new <code>Thread</code> object. This constructor has
268   * the same effect as <code>Thread(null, null, name)</code>.
269   *
270   * @param   name   the name of the new thread.
271   * @see     java.lang.Thread#Thread(java.lang.ThreadGroup,
272   *          java.lang.Runnable, java.lang.String)
273   */
274  public Thread(String name)
275  {
276    this(null, null, name);
277  }
278
279  /**
280   * Allocates a new <code>Thread</code> object. This constructor has
281   * the same effect as <code>Thread(group, target,</code>
282   * <i>gname</i><code>)</code>, where <i>gname</i> is
283   * a newly generated name. Automatically generated names are of the
284   * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
285   *
286   * @param group the group to put the Thread into
287   * @param target the Runnable object to execute
288   * @throws SecurityException if this thread cannot access <code>group</code>
289   * @throws IllegalThreadStateException if group is destroyed
290   * @see #Thread(ThreadGroup, Runnable, String)
291   */
292  public Thread(ThreadGroup group, Runnable target)
293  {
294    this(group, target, gen_name());
295  }
296
297  /**
298   * Allocates a new <code>Thread</code> object. This constructor has
299   * the same effect as <code>Thread(group, null, name)</code>
300   *
301   * @param group the group to put the Thread into
302   * @param name the name for the Thread
303   * @throws NullPointerException if name is null
304   * @throws SecurityException if this thread cannot access <code>group</code>
305   * @throws IllegalThreadStateException if group is destroyed
306   * @see #Thread(ThreadGroup, Runnable, String)
307   */
308  public Thread(ThreadGroup group, String name)
309  {
310    this(group, null, name);
311  }
312
313  /**
314   * Allocates a new <code>Thread</code> object. This constructor has
315   * the same effect as <code>Thread(null, target, name)</code>.
316   *
317   * @param target the Runnable object to execute
318   * @param name the name for the Thread
319   * @throws NullPointerException if name is null
320   * @see #Thread(ThreadGroup, Runnable, String)
321   */
322  public Thread(Runnable target, String name)
323  {
324    this(null, target, name);
325  }
326
327  /**
328   * Allocate a new Thread object, with the specified ThreadGroup and name, and
329   * using the specified Runnable object's <code>run()</code> method to
330   * execute.  If the Runnable object is null, <code>this</code> (which is
331   * a Runnable) is used instead.
332   *
333   * <p>If the ThreadGroup is null, the security manager is checked. If a
334   * manager exists and returns a non-null object for
335   * <code>getThreadGroup</code>, that group is used; otherwise the group
336   * of the creating thread is used. Note that the security manager calls
337   * <code>checkAccess</code> if the ThreadGroup is not null.
338   *
339   * <p>The new Thread will inherit its creator's priority and daemon status.
340   * These can be changed with <code>setPriority</code> and
341   * <code>setDaemon</code>.
342   *
343   * @param group the group to put the Thread into
344   * @param target the Runnable object to execute
345   * @param name the name for the Thread
346   * @throws NullPointerException if name is null
347   * @throws SecurityException if this thread cannot access <code>group</code>
348   * @throws IllegalThreadStateException if group is destroyed
349   * @see Runnable#run()
350   * @see #run()
351   * @see #setDaemon(boolean)
352   * @see #setPriority(int)
353   * @see SecurityManager#checkAccess(ThreadGroup)
354   * @see ThreadGroup#checkAccess()
355   */
356  public Thread(ThreadGroup group, Runnable target, String name)
357  {
358    this(currentThread(), group, target, name, false);
359  }
360
361  /**
362   * Allocate a new Thread object, as if by
363   * <code>Thread(group, null, name)</code>, and give it the specified stack
364   * size, in bytes. The stack size is <b>highly platform independent</b>,
365   * and the virtual machine is free to round up or down, or ignore it
366   * completely.  A higher value might let you go longer before a
367   * <code>StackOverflowError</code>, while a lower value might let you go
368   * longer before an <code>OutOfMemoryError</code>.  Or, it may do absolutely
369   * nothing! So be careful, and expect to need to tune this value if your
370   * virtual machine even supports it.
371   *
372   * @param group the group to put the Thread into
373   * @param target the Runnable object to execute
374   * @param name the name for the Thread
375   * @param size the stack size, in bytes; 0 to be ignored
376   * @throws NullPointerException if name is null
377   * @throws SecurityException if this thread cannot access <code>group</code>
378   * @throws IllegalThreadStateException if group is destroyed
379   * @since 1.4
380   */
381  public Thread(ThreadGroup group, Runnable target, String name, long size)
382  {
383    // Just ignore stackSize for now.
384    this(currentThread(), group, target, name, false);
385  }
386
387  /**
388   * Allocate a new Thread object for threads used internally to the
389   * run time.  Runtime threads should not be members of an
390   * application ThreadGroup, nor should they execute arbitrary user
391   * code as part of the InheritableThreadLocal protocol.
392   *
393   * @param name the name for the Thread
394   * @param noInheritableThreadLocal if true, do not initialize
395   * InheritableThreadLocal variables for this thread.
396   * @throws IllegalThreadStateException if group is destroyed
397   */
398  Thread(String name, boolean noInheritableThreadLocal)
399  {
400    this(null, null, null, name, noInheritableThreadLocal);
401  }
402  
403  private Thread (Thread current, ThreadGroup g, Runnable r, String n, boolean noInheritableThreadLocal)
404  {
405    // Make sure the current thread may create a new thread.
406    checkAccess();
407    
408    // The Class Libraries book says ``threadName cannot be null''.  I
409    // take this to mean NullPointerException.
410    if (n == null)
411      throw new NullPointerException ();
412      
413    if (g == null)
414      {
415        // If CURRENT is null, then we are bootstrapping the first thread. 
416        // Use ThreadGroup.root, the main threadgroup.
417        if (current == null)
418          group = ThreadGroup.root;
419        else
420          group = current.getThreadGroup();
421      }
422    else
423      group = g;
424
425    data = null;
426    interrupt_flag = false;
427    startable_flag = true;
428
429    synchronized (Thread.class)
430      {
431        this.threadId = nextThreadId++;
432      }
433
434    // Always create the ThreadLocalMap when creating a thread; the
435    // previous code did this lazily when getThreadLocals was called,
436    // but this is a divergence from Classpath's implementation of
437    // ThreadLocal.
438    this.locals = new ThreadLocalMap();
439
440    if (current != null)
441      {
442        group.checkAccess();
443
444        daemon = current.isDaemon();
445        int gmax = group.getMaxPriority();
446        int pri = current.getPriority();
447        priority = (gmax < pri ? gmax : pri);
448        contextClassLoader = current.contextClassLoader;
449        // InheritableThreadLocal allows arbitrary user code to be
450        // executed, only do this if our caller desires it.
451        if (!noInheritableThreadLocal)
452          InheritableThreadLocal.newChildThread(this);
453      }
454    else
455      {
456        daemon = false;
457        priority = NORM_PRIORITY;
458      }
459
460    name = n;
461    group.addThread(this);
462    runnable = r;
463
464    initialize_native ();
465  }
466
467  /**
468   * Get the number of active threads in the current Thread's ThreadGroup.
469   * This implementation calls
470   * <code>currentThread().getThreadGroup().activeCount()</code>.
471   *
472   * @return the number of active threads in the current ThreadGroup
473   * @see ThreadGroup#activeCount()
474   */
475  public static int activeCount()
476  {
477    return currentThread().group.activeCount();
478  }
479
480  /**
481   * Check whether the current Thread is allowed to modify this Thread. This
482   * passes the check on to <code>SecurityManager.checkAccess(this)</code>.
483   *
484   * @throws SecurityException if the current Thread cannot modify this Thread
485   * @see SecurityManager#checkAccess(Thread)
486   */
487  public final void checkAccess()
488  {
489    SecurityManager sm = System.getSecurityManager();
490    if (sm != null)
491      sm.checkAccess(this);
492  }
493
494  /**
495   * Count the number of stack frames in this Thread.  The Thread in question
496   * must be suspended when this occurs.
497   *
498   * @return the number of stack frames in this Thread
499   * @throws IllegalThreadStateException if this Thread is not suspended
500   * @deprecated pointless, since suspend is deprecated
501   */
502  public native int countStackFrames();
503
504  /**
505   * Get the currently executing Thread. In the situation that the
506   * currently running thread was created by native code and doesn't
507   * have an associated Thread object yet, a new Thread object is
508   * constructed and associated with the native thread.
509   *
510   * @return the currently executing Thread
511   */
512  public static native Thread currentThread();
513
514  /**
515   * Originally intended to destroy this thread, this method was never
516   * implemented by Sun, and is hence a no-op.
517   *
518   * @deprecated This method was originally intended to simply destroy
519   *             the thread without performing any form of cleanup operation.
520   *             However, it was never implemented.  It is now deprecated
521   *             for the same reason as <code>suspend()</code>,
522   *             <code>stop()</code> and <code>resume()</code>; namely,
523   *             it is prone to deadlocks.  If a thread is destroyed while
524   *             it still maintains a lock on a resource, then this resource
525   *             will remain locked and any attempts by other threads to
526   *             access the resource will result in a deadlock.  Thus, even
527   *             an implemented version of this method would be still be
528   *             deprecated, due to its unsafe nature.
529   * @throws NoSuchMethodError as this method was never implemented.
530   */
531  public void destroy()
532  {
533    throw new NoSuchMethodError();
534  }
535  
536  /**
537   * Print a stack trace of the current thread to stderr using the same
538   * format as Throwable's printStackTrace() method.
539   *
540   * @see Throwable#printStackTrace()
541   */
542  public static void dumpStack()
543  {
544    (new Exception("Stack trace")).printStackTrace();
545  }
546
547  /**
548   * Copy every active thread in the current Thread's ThreadGroup into the
549   * array. Extra threads are silently ignored. This implementation calls
550   * <code>getThreadGroup().enumerate(array)</code>, which may have a
551   * security check, <code>checkAccess(group)</code>.
552   *
553   * @param array the array to place the Threads into
554   * @return the number of Threads placed into the array
555   * @throws NullPointerException if array is null
556   * @throws SecurityException if you cannot access the ThreadGroup
557   * @see ThreadGroup#enumerate(Thread[])
558   * @see #activeCount()
559   * @see SecurityManager#checkAccess(ThreadGroup)
560   */
561  public static int enumerate(Thread[] array)
562  {
563    return currentThread().group.enumerate(array);
564  }
565  
566  /**
567   * Get this Thread's name.
568   *
569   * @return this Thread's name
570   */
571  public final String getName()
572  {
573    return name;
574  }
575
576  /**
577   * Get this Thread's priority.
578   *
579   * @return the Thread's priority
580   */
581  public final int getPriority()
582  {
583    return priority;
584  }
585
586  /**
587   * Get the ThreadGroup this Thread belongs to. If the thread has died, this
588   * returns null.
589   *
590   * @return this Thread's ThreadGroup
591   */
592  public final ThreadGroup getThreadGroup()
593  {
594    return group;
595  }
596
597  /**
598   * Checks whether the current thread holds the monitor on a given object.
599   * This allows you to do <code>assert Thread.holdsLock(obj)</code>.
600   *
601   * @param obj the object to test lock ownership on.
602   * @return true if the current thread is currently synchronized on obj
603   * @throws NullPointerException if obj is null
604   * @since 1.4
605   */
606  public static native boolean holdsLock(Object obj);
607
608  /**
609   * Interrupt this Thread. First, there is a security check,
610   * <code>checkAccess</code>. Then, depending on the current state of the
611   * thread, various actions take place:
612   *
613   * <p>If the thread is waiting because of {@link #wait()},
614   * {@link #sleep(long)}, or {@link #join()}, its <i>interrupt status</i>
615   * will be cleared, and an InterruptedException will be thrown. Notice that
616   * this case is only possible if an external thread called interrupt().
617   *
618   * <p>If the thread is blocked in an interruptible I/O operation, in
619   * {@link java.nio.channels.InterruptibleChannel}, the <i>interrupt
620   * status</i> will be set, and ClosedByInterruptException will be thrown.
621   *
622   * <p>If the thread is blocked on a {@link java.nio.channels.Selector}, the
623   * <i>interrupt status</i> will be set, and the selection will return, with
624   * a possible non-zero value, as though by the wakeup() method.
625   *
626   * <p>Otherwise, the interrupt status will be set.
627   *
628   * @throws SecurityException if you cannot modify this Thread
629   */
630  public native void interrupt();
631
632  /**
633   * Determine whether the current Thread has been interrupted, and clear
634   * the <i>interrupted status</i> in the process.
635   *
636   * @return whether the current Thread has been interrupted
637   * @see #isInterrupted()
638   */
639  public static boolean interrupted()
640  {
641    return currentThread().isInterrupted(true);
642  }
643
644  /**
645   * Determine whether the given Thread has been interrupted, but leave
646   * the <i>interrupted status</i> alone in the process.
647   *
648   * @return whether the Thread has been interrupted
649   * @see #interrupted()
650   */
651  public boolean isInterrupted()
652  {
653    return interrupt_flag;
654  }
655
656  /**
657   * Determine whether this Thread is alive. A thread which is alive has
658   * started and not yet died.
659   *
660   * @return whether this Thread is alive
661   */
662  public final native boolean isAlive();
663
664  /**
665   * Tell whether this is a daemon Thread or not.
666   *
667   * @return whether this is a daemon Thread or not
668   * @see #setDaemon(boolean)
669   */
670  public final boolean isDaemon()
671  {
672    return daemon;
673  }
674
675  /**
676   * Wait forever for the Thread in question to die.
677   *
678   * @throws InterruptedException if the Thread is interrupted; it's
679   *         <i>interrupted status</i> will be cleared
680   */
681  public final void join() throws InterruptedException
682  {
683    join(0, 0);
684  }
685
686  /**
687   * Wait the specified amount of time for the Thread in question to die.
688   *
689   * @param ms the number of milliseconds to wait, or 0 for forever
690   * @throws InterruptedException if the Thread is interrupted; it's
691   *         <i>interrupted status</i> will be cleared
692   */
693  public final void join(long ms) throws InterruptedException
694  {
695    join(ms, 0);
696  }
697
698  /**
699   * Wait the specified amount of time for the Thread in question to die.
700   *
701   * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
702   * not offer that fine a grain of timing resolution. Besides, there is
703   * no guarantee that this thread can start up immediately when time expires,
704   * because some other thread may be active.  So don't expect real-time
705   * performance.
706   *
707   * @param ms the number of milliseconds to wait, or 0 for forever
708   * @param ns the number of extra nanoseconds to sleep (0-999999)
709   * @throws InterruptedException if the Thread is interrupted; it's
710   *         <i>interrupted status</i> will be cleared
711   * @throws IllegalArgumentException if ns is invalid
712   * @XXX A ThreadListener would be nice, to make this efficient.
713   */
714  public final native void join(long ms, int ns)
715    throws InterruptedException;
716
717  /**
718   * Resume this Thread.  If the thread is not suspended, this method does
719   * nothing. To mirror suspend(), there may be a security check:
720   * <code>checkAccess</code>.
721   *
722   * @throws SecurityException if you cannot resume the Thread
723   * @see #checkAccess()
724   * @see #suspend()
725   * @deprecated pointless, since suspend is deprecated
726   */
727  public final native void resume();
728
729  private final native void finish_();
730
731  /**
732   * Determine whether the given Thread has been interrupted, but leave
733   * the <i>interrupted status</i> alone in the process.
734   *
735   * @return whether the current Thread has been interrupted
736   * @see #interrupted()
737   */
738  private boolean isInterrupted(boolean clear_flag)
739  {
740    boolean r = interrupt_flag;
741    if (clear_flag && r)
742      {
743        // Only clear the flag if we saw it as set. Otherwise this could 
744        // potentially cause us to miss an interrupt in a race condition, 
745        // because this method is not synchronized.
746        interrupt_flag = false;
747      }
748    return r;
749  }
750  
751  /**
752   * The method of Thread that will be run if there is no Runnable object
753   * associated with the Thread. Thread's implementation does nothing at all.
754   *
755   * @see #start()
756   * @see #Thread(ThreadGroup, Runnable, String)
757   */
758  public void run()
759  {
760    if (runnable != null)
761      runnable.run();
762  }
763
764  /**
765   * Set the daemon status of this Thread.  If this is a daemon Thread, then
766   * the VM may exit even if it is still running.  This may only be called
767   * before the Thread starts running. There may be a security check,
768   * <code>checkAccess</code>.
769   *
770   * @param daemon whether this should be a daemon thread or not
771   * @throws SecurityException if you cannot modify this Thread
772   * @throws IllegalThreadStateException if the Thread is active
773   * @see #isDaemon()
774   * @see #checkAccess()
775   */
776  public final void setDaemon(boolean daemon)
777  {
778    if (!startable_flag)
779      throw new IllegalThreadStateException();
780    checkAccess();
781    this.daemon = daemon;
782  }
783
784  /**
785   * Returns the context classloader of this Thread. The context
786   * classloader can be used by code that want to load classes depending
787   * on the current thread. Normally classes are loaded depending on
788   * the classloader of the current class. There may be a security check
789   * for <code>RuntimePermission("getClassLoader")</code> if the caller's
790   * class loader is not null or an ancestor of this thread's context class
791   * loader.
792   *
793   * @return the context class loader
794   * @throws SecurityException when permission is denied
795   * @see #setContextClassLoader(ClassLoader)
796   * @since 1.2
797   */
798  public synchronized ClassLoader getContextClassLoader()
799  {
800    if (contextClassLoader == null)
801      contextClassLoader = ClassLoader.getSystemClassLoader();
802
803    // Check if we may get the classloader
804    SecurityManager sm = System.getSecurityManager();
805    if (contextClassLoader != null && sm != null)
806      {
807        // Get the calling classloader
808        ClassLoader cl = VMStackWalker.getCallingClassLoader();
809        if (cl != null && !cl.isAncestorOf(contextClassLoader))
810          sm.checkPermission(new RuntimePermission("getClassLoader"));
811      }
812    return contextClassLoader;
813  }
814
815  /**
816   * Sets the context classloader for this Thread. When not explicitly set,
817   * the context classloader for a thread is the same as the context
818   * classloader of the thread that created this thread. The first thread has
819   * as context classloader the system classloader. There may be a security
820   * check for <code>RuntimePermission("setContextClassLoader")</code>.
821   *
822   * @param classloader the new context class loader
823   * @throws SecurityException when permission is denied
824   * @see #getContextClassLoader()
825   * @since 1.2
826   */
827  public synchronized void setContextClassLoader(ClassLoader classloader)
828  {
829    SecurityManager sm = System.getSecurityManager();
830    if (sm != null)
831      sm.checkPermission(new RuntimePermission("setContextClassLoader"));
832    this.contextClassLoader = classloader;
833  }
834
835  /**
836   * Set this Thread's name.  There may be a security check,
837   * <code>checkAccess</code>.
838   *
839   * @param name the new name for this Thread
840   * @throws NullPointerException if name is null
841   * @throws SecurityException if you cannot modify this Thread
842   */
843  public final void setName(String name)
844  {
845    checkAccess();
846    // The Class Libraries book says ``threadName cannot be null''.  I
847    // take this to mean NullPointerException.
848    if (name == null)
849      throw new NullPointerException();
850    this.name = name;
851  }
852
853  /**
854   * Yield to another thread. The Thread will not lose any locks it holds
855   * during this time. There are no guarantees which thread will be
856   * next to run, and it could even be this one, but most VMs will choose
857   * the highest priority thread that has been waiting longest.
858   */
859  public static native void yield();
860
861  /**
862   * Suspend the current Thread's execution for the specified amount of
863   * time. The Thread will not lose any locks it has during this time. There
864   * are no guarantees which thread will be next to run, but most VMs will
865   * choose the highest priority thread that has been waiting longest.
866   *
867   * @param ms the number of milliseconds to sleep, or 0 for forever
868   * @throws InterruptedException if the Thread is (or was) interrupted;
869   *         it's <i>interrupted status</i> will be cleared
870   * @throws IllegalArgumentException if ms is negative
871   * @see #interrupt()
872   * @see #notify()
873   * @see #wait(long)
874   */
875  public static void sleep(long ms) throws InterruptedException
876  {
877    sleep(ms, 0);
878  }
879
880  /**
881   * Suspend the current Thread's execution for the specified amount of
882   * time. The Thread will not lose any locks it has during this time. There
883   * are no guarantees which thread will be next to run, but most VMs will
884   * choose the highest priority thread that has been waiting longest.
885   * <p>
886   * Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs
887   * do not offer that fine a grain of timing resolution. When ms is
888   * zero and ns is non-zero the Thread will sleep for at least one
889   * milli second. There is no guarantee that this thread can start up
890   * immediately when time expires, because some other thread may be
891   * active.  So don't expect real-time performance.
892   *
893   * @param ms the number of milliseconds to sleep, or 0 for forever
894   * @param ns the number of extra nanoseconds to sleep (0-999999)
895   * @throws InterruptedException if the Thread is (or was) interrupted;
896   *         it's <i>interrupted status</i> will be cleared
897   * @throws IllegalArgumentException if ms or ns is negative
898   *         or ns is larger than 999999.
899   * @see #interrupt()
900   * @see #notify()
901   * @see #wait(long, int)
902   */
903  public static native void sleep(long timeout, int nanos)
904    throws InterruptedException;
905
906  /**
907   * Start this Thread, calling the run() method of the Runnable this Thread
908   * was created with, or else the run() method of the Thread itself. This
909   * is the only way to start a new thread; calling run by yourself will just
910   * stay in the same thread. The virtual machine will remove the thread from
911   * its thread group when the run() method completes.
912   *
913   * @throws IllegalThreadStateException if the thread has already started
914   * @see #run()
915   */
916  public native void start();
917
918  /**
919   * Cause this Thread to stop abnormally because of the throw of a ThreadDeath
920   * error. If you stop a Thread that has not yet started, it will stop
921   * immediately when it is actually started.
922   *
923   * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
924   * leave data in bad states.  Hence, there is a security check:
925   * <code>checkAccess(this)</code>, plus another one if the current thread
926   * is not this: <code>RuntimePermission("stopThread")</code>. If you must
927   * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
928   * ThreadDeath is the only exception which does not print a stack trace when
929   * the thread dies.
930   *
931   * @throws SecurityException if you cannot stop the Thread
932   * @see #interrupt()
933   * @see #checkAccess()
934   * @see #start()
935   * @see ThreadDeath
936   * @see ThreadGroup#uncaughtException(Thread, Throwable)
937   * @see SecurityManager#checkAccess(Thread)
938   * @see SecurityManager#checkPermission(Permission)
939   * @deprecated unsafe operation, try not to use
940   */
941  public final void stop()
942  {
943    // Argument doesn't matter, because this is no longer
944    // supported.
945    stop(null);
946  }
947
948  /**
949   * Cause this Thread to stop abnormally and throw the specified exception.
950   * If you stop a Thread that has not yet started, the stop is ignored
951   * (contrary to what the JDK documentation says).
952   * <b>WARNING</b>This bypasses Java security, and can throw a checked
953   * exception which the call stack is unprepared to handle. Do not abuse
954   * this power.
955   *
956   * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
957   * leave data in bad states.  Hence, there is a security check:
958   * <code>checkAccess(this)</code>, plus another one if the current thread
959   * is not this: <code>RuntimePermission("stopThread")</code>. If you must
960   * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
961   * ThreadDeath is the only exception which does not print a stack trace when
962   * the thread dies.
963   *
964   * @param t the Throwable to throw when the Thread dies
965   * @throws SecurityException if you cannot stop the Thread
966   * @throws NullPointerException in the calling thread, if t is null
967   * @see #interrupt()
968   * @see #checkAccess()
969   * @see #start()
970   * @see ThreadDeath
971   * @see ThreadGroup#uncaughtException(Thread, Throwable)
972   * @see SecurityManager#checkAccess(Thread)
973   * @see SecurityManager#checkPermission(Permission)
974   * @deprecated unsafe operation, try not to use
975   */
976  public final native void stop(Throwable t);
977
978  /**
979   * Suspend this Thread.  It will not come back, ever, unless it is resumed.
980   *
981   * <p>This is inherently unsafe, as the suspended thread still holds locks,
982   * and can potentially deadlock your program.  Hence, there is a security
983   * check: <code>checkAccess</code>.
984   *
985   * @throws SecurityException if you cannot suspend the Thread
986   * @see #checkAccess()
987   * @see #resume()
988   * @deprecated unsafe operation, try not to use
989   */
990  public final native void suspend();
991
992  /**
993   * Set this Thread's priority. There may be a security check,
994   * <code>checkAccess</code>, then the priority is set to the smaller of
995   * priority and the ThreadGroup maximum priority.
996   *
997   * @param priority the new priority for this Thread
998   * @throws IllegalArgumentException if priority exceeds MIN_PRIORITY or
999   *         MAX_PRIORITY
1000   * @throws SecurityException if you cannot modify this Thread
1001   * @see #getPriority()
1002   * @see #checkAccess()
1003   * @see ThreadGroup#getMaxPriority()
1004   * @see #MIN_PRIORITY
1005   * @see #MAX_PRIORITY
1006   */
1007  public final native void setPriority(int newPriority);
1008
1009  /**
1010   * Returns a string representation of this thread, including the
1011   * thread's name, priority, and thread group.
1012   *
1013   * @return a human-readable String representing this Thread
1014   */
1015  public String toString()
1016  {
1017    return ("Thread[" + name + "," + priority + ","
1018            + (group == null ? "" : group.getName()) + "]");
1019  }
1020
1021  private final native void initialize_native();
1022
1023  private final native static String gen_name();
1024
1025  /**
1026   * Returns the map used by ThreadLocal to store the thread local values.
1027   */
1028  static ThreadLocalMap getThreadLocals()
1029  {
1030    Thread thread = currentThread();
1031    ThreadLocalMap locals = thread.locals;
1032
1033    return locals;
1034  }
1035
1036  /** 
1037   * Assigns the given <code>UncaughtExceptionHandler</code> to this
1038   * thread.  This will then be called if the thread terminates due
1039   * to an uncaught exception, pre-empting that of the
1040   * <code>ThreadGroup</code>.
1041   *
1042   * @param h the handler to use for this thread.
1043   * @throws SecurityException if the current thread can't modify this thread.
1044   * @since 1.5 
1045   */
1046  public void setUncaughtExceptionHandler(UncaughtExceptionHandler h)
1047  {
1048    SecurityManager sm = SecurityManager.current; // Be thread-safe.
1049    if (sm != null)
1050      sm.checkAccess(this);    
1051    exceptionHandler = h;
1052  }
1053
1054  /** 
1055   * <p>
1056   * Returns the handler used when this thread terminates due to an
1057   * uncaught exception.  The handler used is determined by the following:
1058   * </p>
1059   * <ul>
1060   * <li>If this thread has its own handler, this is returned.</li>
1061   * <li>If not, then the handler of the thread's <code>ThreadGroup</code>
1062   * object is returned.</li>
1063   * <li>If both are unavailable, then <code>null</code> is returned
1064   *     (which can only happen when the thread was terminated since
1065   *      then it won't have an associated thread group anymore).</li>
1066   * </ul>
1067   * 
1068   * @return the appropriate <code>UncaughtExceptionHandler</code> or
1069   *         <code>null</code> if one can't be obtained.
1070   * @since 1.5 
1071   */
1072  public UncaughtExceptionHandler getUncaughtExceptionHandler()
1073  {
1074    // FIXME: if thread is dead, should return null...
1075    return exceptionHandler != null ? exceptionHandler : group;
1076  }
1077
1078  /** 
1079   * <p>
1080   * Sets the default uncaught exception handler used when one isn't
1081   * provided by the thread or its associated <code>ThreadGroup</code>.
1082   * This exception handler is used when the thread itself does not
1083   * have an exception handler, and the thread's <code>ThreadGroup</code>
1084   * does not override this default mechanism with its own.  As the group
1085   * calls this handler by default, this exception handler should not defer
1086   * to that of the group, as it may lead to infinite recursion.
1087   * </p>
1088   * <p>
1089   * Uncaught exception handlers are used when a thread terminates due to
1090   * an uncaught exception.  Replacing this handler allows default code to
1091   * be put in place for all threads in order to handle this eventuality.
1092   * </p>
1093   *
1094   * @param h the new default uncaught exception handler to use.
1095   * @throws SecurityException if a security manager is present and
1096   *                           disallows the runtime permission
1097   *                           "setDefaultUncaughtExceptionHandler".
1098   * @since 1.5 
1099   */
1100  public static void 
1101    setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler h)
1102  {
1103    SecurityManager sm = SecurityManager.current; // Be thread-safe.
1104    if (sm != null)
1105      sm.checkPermission(new RuntimePermission("setDefaultUncaughtExceptionHandler"));    
1106    defaultHandler = h;
1107  }
1108
1109  /** 
1110   * Returns the handler used by default when a thread terminates
1111   * unexpectedly due to an exception, or <code>null</code> if one doesn't
1112   * exist.
1113   *
1114   * @return the default uncaught exception handler.
1115   * @since 1.5 
1116   */
1117  public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
1118  {
1119    return defaultHandler;
1120  }
1121  
1122  /** 
1123   * Returns the unique identifier for this thread.  This ID is generated
1124   * on thread creation, and may be re-used on its death.
1125   *
1126   * @return a positive long number representing the thread's ID.
1127   * @since 1.5 
1128   */
1129  public long getId()
1130  {
1131    return threadId;
1132  }
1133
1134  /**
1135   * <p>
1136   * This interface is used to handle uncaught exceptions
1137   * which cause a <code>Thread</code> to terminate.  When
1138   * a thread, t, is about to terminate due to an uncaught
1139   * exception, the virtual machine looks for a class which
1140   * implements this interface, in order to supply it with
1141   * the dying thread and its uncaught exception.
1142   * </p>
1143   * <p>
1144   * The virtual machine makes two attempts to find an
1145   * appropriate handler for the uncaught exception, in
1146   * the following order:
1147   * </p>
1148   * <ol>
1149   * <li>
1150   * <code>t.getUncaughtExceptionHandler()</code> --
1151   * the dying thread is queried first for a handler
1152   * specific to that thread.
1153   * </li>
1154   * <li>
1155   * <code>t.getThreadGroup()</code> --
1156   * the thread group of the dying thread is used to
1157   * handle the exception.  If the thread group has
1158   * no special requirements for handling the exception,
1159   * it may simply forward it on to
1160   * <code>Thread.getDefaultUncaughtExceptionHandler()</code>,
1161   * the default handler, which is used as a last resort.
1162   * </li>
1163   * </ol>
1164   * <p>
1165   * The first handler found is the one used to handle
1166   * the uncaught exception.
1167   * </p>
1168   *
1169   * @author Tom Tromey <tromey@redhat.com>
1170   * @author Andrew John Hughes <gnu_andrew@member.fsf.org>
1171   * @since 1.5
1172   * @see Thread#getUncaughtExceptionHandler()
1173   * @see Thread#setUncaughtExceptionHandler(UncaughtExceptionHandler)
1174   * @see Thread#getDefaultUncaughtExceptionHandler()
1175   * @see
1176   * Thread#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)
1177   */
1178  public interface UncaughtExceptionHandler
1179  {
1180    /**
1181     * Invoked by the virtual machine with the dying thread
1182     * and the uncaught exception.  Any exceptions thrown
1183     * by this method are simply ignored by the virtual
1184     * machine.
1185     *
1186     * @param thr the dying thread.
1187     * @param exc the uncaught exception.
1188     */
1189    void uncaughtException(Thread thr, Throwable exc);
1190  }
1191
1192  /** 
1193   * <p>
1194   * Represents the current state of a thread, according to the VM rather
1195   * than the operating system.  It can be one of the following:
1196   * </p>
1197   * <ul>
1198   * <li>NEW -- The thread has just been created but is not yet running.</li>
1199   * <li>RUNNABLE -- The thread is currently running or can be scheduled
1200   * to run.</li>
1201   * <li>BLOCKED -- The thread is blocked waiting on an I/O operation
1202   * or to obtain a lock.</li>
1203   * <li>WAITING -- The thread is waiting indefinitely for another thread
1204   * to do something.</li>
1205   * <li>TIMED_WAITING -- The thread is waiting for a specific amount of time
1206   * for another thread to do something.</li>
1207   * <li>TERMINATED -- The thread has exited.</li>
1208   * </ul>
1209   *
1210   * @since 1.5 
1211   */
1212  public enum State
1213  {
1214    BLOCKED, NEW, RUNNABLE, TERMINATED, TIMED_WAITING, WAITING;
1215  }
1216
1217
1218  /**
1219   * Returns the current state of the thread.  This
1220   * is designed for monitoring thread behaviour, rather
1221   * than for synchronization control.
1222   *
1223   * @return the current thread state.
1224   */
1225  public native State getState();
1226
1227  /**
1228   * <p>
1229   * Returns a map of threads to stack traces for each
1230   * live thread.  The keys of the map are {@link Thread}
1231   * objects, which map to arrays of {@link StackTraceElement}s.
1232   * The results obtained from Calling this method are
1233   * equivalent to calling {@link getStackTrace()} on each
1234   * thread in succession.  Threads may be executing while
1235   * this takes place, and the results represent a snapshot
1236   * of the thread at the time its {@link getStackTrace()}
1237   * method is called.
1238   * </p>
1239   * <p>
1240   * The stack trace information contains the methods called
1241   * by the thread, with the most recent method forming the
1242   * first element in the array.  The array will be empty
1243   * if the virtual machine can not obtain information on the
1244   * thread. 
1245   * </p>
1246   * <p>
1247   * To execute this method, the current security manager
1248   * (if one exists) must allow both the
1249   * <code>"getStackTrace"</code> and
1250   * <code>"modifyThreadGroup"</code> {@link RuntimePermission}s.
1251   * </p>
1252   * 
1253   * @return a map of threads to arrays of {@link StackTraceElement}s.
1254   * @throws SecurityException if a security manager exists, and
1255   *                           prevents either or both the runtime
1256   *                           permissions specified above.
1257   * @since 1.5
1258   * @see #getStackTrace()
1259   */
1260  public static Map<Thread, StackTraceElement[]> getAllStackTraces()
1261  {
1262    ThreadGroup group = currentThread().group;
1263    while (group.getParent() != null)
1264      group = group.getParent();
1265    int arraySize = group.activeCount();
1266    Thread[] threadList = new Thread[arraySize];
1267    int filled = group.enumerate(threadList);
1268    while (filled == arraySize)
1269      {
1270        arraySize *= 2;
1271        threadList = new Thread[arraySize];
1272        filled = group.enumerate(threadList);
1273      }
1274    Map traces = new HashMap();
1275    for (int a = 0; a < filled; ++a)
1276      traces.put(threadList[a],
1277                 threadList[a].getStackTrace());
1278    return traces;
1279  }
1280
1281  /**
1282   * <p>
1283   * Returns an array of {@link StackTraceElement}s
1284   * representing the current stack trace of this thread.
1285   * The first element of the array is the most recent
1286   * method called, and represents the top of the stack.
1287   * The elements continue in this order, with the last
1288   * element representing the bottom of the stack.
1289   * </p>
1290   * <p>
1291   * A zero element array is returned for threads which
1292   * have not yet started (and thus have not yet executed
1293   * any methods) or for those which have terminated.
1294   * Where the virtual machine can not obtain a trace for
1295   * the thread, an empty array is also returned.  The
1296   * virtual machine may also omit some methods from the
1297   * trace in non-zero arrays.
1298   * </p>
1299   * <p>
1300   * To execute this method, the current security manager
1301   * (if one exists) must allow both the
1302   * <code>"getStackTrace"</code> and
1303   * <code>"modifyThreadGroup"</code> {@link RuntimePermission}s.
1304   * </p>
1305   *
1306   * @return a stack trace for this thread.
1307   * @throws SecurityException if a security manager exists, and
1308   *                           prevents the use of the
1309   *                           <code>"getStackTrace"</code>
1310   *                           permission.
1311   * @since 1.5
1312   * @see #getAllStackTraces()
1313   */
1314  public StackTraceElement[] getStackTrace()
1315  {
1316    SecurityManager sm = SecurityManager.current; // Be thread-safe.
1317    if (sm != null)
1318      sm.checkPermission(new RuntimePermission("getStackTrace"));
1319
1320    // Calling java.lang.management via reflection means that
1321    // javax.management be overridden in the endorsed directory.
1322
1323    // This is the equivalent code:
1324    //
1325    //     ThreadMXBean bean = ManagementFactory.getThreadMXBean();
1326    //     ThreadInfo info = bean.getThreadInfo(getId(), Integer.MAX_VALUE);
1327    //     return info.getStackTrace();
1328
1329    try
1330      {
1331        try
1332          {
1333            Object bean 
1334              = (Class.forName("java.lang.management.ManagementFactory")
1335                 .getDeclaredMethod("getThreadMXBean")
1336                 .invoke(null));
1337            Object info = bean.getClass()
1338              .getDeclaredMethod("getThreadInfo", long.class, int.class)
1339              .invoke(bean, new Long(getId()), new Integer(Integer.MAX_VALUE));
1340            Object trace = info.getClass()
1341              .getDeclaredMethod("getStackTrace").invoke(info);
1342            return (StackTraceElement[])trace;
1343          }
1344        catch (InvocationTargetException e)
1345          {
1346            throw (Exception)e.getTargetException();
1347          }
1348      }
1349    catch (UnsupportedOperationException e)
1350      {
1351        throw e;
1352      }
1353    catch (Exception e)
1354      {
1355        throw new UnsupportedOperationException(e);
1356      }
1357  }
1358}