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    
005    This file is part of GNU Classpath.
006    
007    GNU Classpath is free software; you can redistribute it and/or modify
008    it under the terms of the GNU General Public License as published by
009    the Free Software Foundation; either version 2, or (at your option)
010    any later version.
011    
012    GNU Classpath is distributed in the hope that it will be useful, but
013    WITHOUT ANY WARRANTY; without even the implied warranty of
014    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
015    General Public License for more details.
016    
017    You should have received a copy of the GNU General Public License
018    along with GNU Classpath; see the file COPYING.  If not, write to the
019    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
020    02110-1301 USA.
021    
022    Linking this library statically or dynamically with other modules is
023    making a combined work based on this library.  Thus, the terms and
024    conditions of the GNU General Public License cover the whole
025    combination.
026    
027    As a special exception, the copyright holders of this library give you
028    permission to link this library with independent modules to produce an
029    executable, regardless of the license terms of these independent
030    modules, and to copy and distribute the resulting executable under
031    terms of your choice, provided that you also meet, for each linked
032    independent module, the terms and conditions of the license of that
033    module.  An independent module is a module which is not derived from
034    or based on this library.  If you modify this library, you may extend
035    this exception to your version of the library, but you are not
036    obligated to do so.  If you do not wish to do so, delete this
037    exception statement from your version. */
038    
039    package java.lang;
040    
041    import gnu.classpath.VMStackWalker;
042    import gnu.gcj.RawData;
043    import gnu.gcj.RawDataManaged;
044    import gnu.java.util.WeakIdentityHashMap;
045    
046    import java.lang.management.ManagementFactory;
047    import java.lang.management.ThreadInfo;
048    import java.lang.management.ThreadMXBean;
049    
050    import java.util.HashMap;
051    import java.util.Map;
052    
053    import java.lang.reflect.InvocationTargetException;
054    import 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     */
104    public 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      WeakIdentityHashMap 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        if (current != null)
435          {
436            group.checkAccess();
437    
438            daemon = current.isDaemon();
439            int gmax = group.getMaxPriority();
440            int pri = current.getPriority();
441            priority = (gmax < pri ? gmax : pri);
442            contextClassLoader = current.contextClassLoader;
443            // InheritableThreadLocal allows arbitrary user code to be
444            // executed, only do this if our caller desires it.
445            if (!noInheritableThreadLocal)
446              InheritableThreadLocal.newChildThread(this);
447          }
448        else
449          {
450            daemon = false;
451            priority = NORM_PRIORITY;
452          }
453    
454        name = n;
455        group.addThread(this);
456        runnable = r;
457    
458        initialize_native ();
459      }
460    
461      /**
462       * Get the number of active threads in the current Thread's ThreadGroup.
463       * This implementation calls
464       * <code>currentThread().getThreadGroup().activeCount()</code>.
465       *
466       * @return the number of active threads in the current ThreadGroup
467       * @see ThreadGroup#activeCount()
468       */
469      public static int activeCount()
470      {
471        return currentThread().group.activeCount();
472      }
473    
474      /**
475       * Check whether the current Thread is allowed to modify this Thread. This
476       * passes the check on to <code>SecurityManager.checkAccess(this)</code>.
477       *
478       * @throws SecurityException if the current Thread cannot modify this Thread
479       * @see SecurityManager#checkAccess(Thread)
480       */
481      public final void checkAccess()
482      {
483        SecurityManager sm = System.getSecurityManager();
484        if (sm != null)
485          sm.checkAccess(this);
486      }
487    
488      /**
489       * Count the number of stack frames in this Thread.  The Thread in question
490       * must be suspended when this occurs.
491       *
492       * @return the number of stack frames in this Thread
493       * @throws IllegalThreadStateException if this Thread is not suspended
494       * @deprecated pointless, since suspend is deprecated
495       */
496      public native int countStackFrames();
497    
498      /**
499       * Get the currently executing Thread. In the situation that the
500       * currently running thread was created by native code and doesn't
501       * have an associated Thread object yet, a new Thread object is
502       * constructed and associated with the native thread.
503       *
504       * @return the currently executing Thread
505       */
506      public static native Thread currentThread();
507    
508      /**
509       * Originally intended to destroy this thread, this method was never
510       * implemented by Sun, and is hence a no-op.
511       *
512       * @deprecated This method was originally intended to simply destroy
513       *             the thread without performing any form of cleanup operation.
514       *             However, it was never implemented.  It is now deprecated
515       *             for the same reason as <code>suspend()</code>,
516       *             <code>stop()</code> and <code>resume()</code>; namely,
517       *             it is prone to deadlocks.  If a thread is destroyed while
518       *             it still maintains a lock on a resource, then this resource
519       *             will remain locked and any attempts by other threads to
520       *             access the resource will result in a deadlock.  Thus, even
521       *             an implemented version of this method would be still be
522       *             deprecated, due to its unsafe nature.
523       * @throws NoSuchMethodError as this method was never implemented.
524       */
525      public void destroy()
526      {
527        throw new NoSuchMethodError();
528      }
529      
530      /**
531       * Print a stack trace of the current thread to stderr using the same
532       * format as Throwable's printStackTrace() method.
533       *
534       * @see Throwable#printStackTrace()
535       */
536      public static void dumpStack()
537      {
538        (new Exception("Stack trace")).printStackTrace();
539      }
540    
541      /**
542       * Copy every active thread in the current Thread's ThreadGroup into the
543       * array. Extra threads are silently ignored. This implementation calls
544       * <code>getThreadGroup().enumerate(array)</code>, which may have a
545       * security check, <code>checkAccess(group)</code>.
546       *
547       * @param array the array to place the Threads into
548       * @return the number of Threads placed into the array
549       * @throws NullPointerException if array is null
550       * @throws SecurityException if you cannot access the ThreadGroup
551       * @see ThreadGroup#enumerate(Thread[])
552       * @see #activeCount()
553       * @see SecurityManager#checkAccess(ThreadGroup)
554       */
555      public static int enumerate(Thread[] array)
556      {
557        return currentThread().group.enumerate(array);
558      }
559      
560      /**
561       * Get this Thread's name.
562       *
563       * @return this Thread's name
564       */
565      public final String getName()
566      {
567        return name;
568      }
569    
570      /**
571       * Get this Thread's priority.
572       *
573       * @return the Thread's priority
574       */
575      public final int getPriority()
576      {
577        return priority;
578      }
579    
580      /**
581       * Get the ThreadGroup this Thread belongs to. If the thread has died, this
582       * returns null.
583       *
584       * @return this Thread's ThreadGroup
585       */
586      public final ThreadGroup getThreadGroup()
587      {
588        return group;
589      }
590    
591      /**
592       * Checks whether the current thread holds the monitor on a given object.
593       * This allows you to do <code>assert Thread.holdsLock(obj)</code>.
594       *
595       * @param obj the object to test lock ownership on.
596       * @return true if the current thread is currently synchronized on obj
597       * @throws NullPointerException if obj is null
598       * @since 1.4
599       */
600      public static native boolean holdsLock(Object obj);
601    
602      /**
603       * Interrupt this Thread. First, there is a security check,
604       * <code>checkAccess</code>. Then, depending on the current state of the
605       * thread, various actions take place:
606       *
607       * <p>If the thread is waiting because of {@link #wait()},
608       * {@link #sleep(long)}, or {@link #join()}, its <i>interrupt status</i>
609       * will be cleared, and an InterruptedException will be thrown. Notice that
610       * this case is only possible if an external thread called interrupt().
611       *
612       * <p>If the thread is blocked in an interruptible I/O operation, in
613       * {@link java.nio.channels.InterruptibleChannel}, the <i>interrupt
614       * status</i> will be set, and ClosedByInterruptException will be thrown.
615       *
616       * <p>If the thread is blocked on a {@link java.nio.channels.Selector}, the
617       * <i>interrupt status</i> will be set, and the selection will return, with
618       * a possible non-zero value, as though by the wakeup() method.
619       *
620       * <p>Otherwise, the interrupt status will be set.
621       *
622       * @throws SecurityException if you cannot modify this Thread
623       */
624      public native void interrupt();
625    
626      /**
627       * Determine whether the current Thread has been interrupted, and clear
628       * the <i>interrupted status</i> in the process.
629       *
630       * @return whether the current Thread has been interrupted
631       * @see #isInterrupted()
632       */
633      public static boolean interrupted()
634      {
635        return currentThread().isInterrupted(true);
636      }
637    
638      /**
639       * Determine whether the given Thread has been interrupted, but leave
640       * the <i>interrupted status</i> alone in the process.
641       *
642       * @return whether the Thread has been interrupted
643       * @see #interrupted()
644       */
645      public boolean isInterrupted()
646      {
647        return interrupt_flag;
648      }
649    
650      /**
651       * Determine whether this Thread is alive. A thread which is alive has
652       * started and not yet died.
653       *
654       * @return whether this Thread is alive
655       */
656      public final native boolean isAlive();
657    
658      /**
659       * Tell whether this is a daemon Thread or not.
660       *
661       * @return whether this is a daemon Thread or not
662       * @see #setDaemon(boolean)
663       */
664      public final boolean isDaemon()
665      {
666        return daemon;
667      }
668    
669      /**
670       * Wait forever for the Thread in question to die.
671       *
672       * @throws InterruptedException if the Thread is interrupted; it's
673       *         <i>interrupted status</i> will be cleared
674       */
675      public final void join() throws InterruptedException
676      {
677        join(0, 0);
678      }
679    
680      /**
681       * Wait the specified amount of time for the Thread in question to die.
682       *
683       * @param ms the number of milliseconds to wait, or 0 for forever
684       * @throws InterruptedException if the Thread is interrupted; it's
685       *         <i>interrupted status</i> will be cleared
686       */
687      public final void join(long ms) throws InterruptedException
688      {
689        join(ms, 0);
690      }
691    
692      /**
693       * Wait the specified amount of time for the Thread in question to die.
694       *
695       * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
696       * not offer that fine a grain of timing resolution. Besides, there is
697       * no guarantee that this thread can start up immediately when time expires,
698       * because some other thread may be active.  So don't expect real-time
699       * performance.
700       *
701       * @param ms the number of milliseconds to wait, or 0 for forever
702       * @param ns the number of extra nanoseconds to sleep (0-999999)
703       * @throws InterruptedException if the Thread is interrupted; it's
704       *         <i>interrupted status</i> will be cleared
705       * @throws IllegalArgumentException if ns is invalid
706       * @XXX A ThreadListener would be nice, to make this efficient.
707       */
708      public final native void join(long ms, int ns)
709        throws InterruptedException;
710    
711      /**
712       * Resume this Thread.  If the thread is not suspended, this method does
713       * nothing. To mirror suspend(), there may be a security check:
714       * <code>checkAccess</code>.
715       *
716       * @throws SecurityException if you cannot resume the Thread
717       * @see #checkAccess()
718       * @see #suspend()
719       * @deprecated pointless, since suspend is deprecated
720       */
721      public final native void resume();
722    
723      private final native void finish_();
724    
725      /**
726       * Determine whether the given Thread has been interrupted, but leave
727       * the <i>interrupted status</i> alone in the process.
728       *
729       * @return whether the current Thread has been interrupted
730       * @see #interrupted()
731       */
732      private boolean isInterrupted(boolean clear_flag)
733      {
734        boolean r = interrupt_flag;
735        if (clear_flag && r)
736          {
737            // Only clear the flag if we saw it as set. Otherwise this could 
738            // potentially cause us to miss an interrupt in a race condition, 
739            // because this method is not synchronized.
740            interrupt_flag = false;
741          }
742        return r;
743      }
744      
745      /**
746       * The method of Thread that will be run if there is no Runnable object
747       * associated with the Thread. Thread's implementation does nothing at all.
748       *
749       * @see #start()
750       * @see #Thread(ThreadGroup, Runnable, String)
751       */
752      public void run()
753      {
754        if (runnable != null)
755          runnable.run();
756      }
757    
758      /**
759       * Set the daemon status of this Thread.  If this is a daemon Thread, then
760       * the VM may exit even if it is still running.  This may only be called
761       * before the Thread starts running. There may be a security check,
762       * <code>checkAccess</code>.
763       *
764       * @param daemon whether this should be a daemon thread or not
765       * @throws SecurityException if you cannot modify this Thread
766       * @throws IllegalThreadStateException if the Thread is active
767       * @see #isDaemon()
768       * @see #checkAccess()
769       */
770      public final void setDaemon(boolean daemon)
771      {
772        if (!startable_flag)
773          throw new IllegalThreadStateException();
774        checkAccess();
775        this.daemon = daemon;
776      }
777    
778      /**
779       * Returns the context classloader of this Thread. The context
780       * classloader can be used by code that want to load classes depending
781       * on the current thread. Normally classes are loaded depending on
782       * the classloader of the current class. There may be a security check
783       * for <code>RuntimePermission("getClassLoader")</code> if the caller's
784       * class loader is not null or an ancestor of this thread's context class
785       * loader.
786       *
787       * @return the context class loader
788       * @throws SecurityException when permission is denied
789       * @see #setContextClassLoader(ClassLoader)
790       * @since 1.2
791       */
792      public synchronized ClassLoader getContextClassLoader()
793      {
794        if (contextClassLoader == null)
795          contextClassLoader = ClassLoader.getSystemClassLoader();
796    
797        // Check if we may get the classloader
798        SecurityManager sm = System.getSecurityManager();
799        if (contextClassLoader != null && sm != null)
800          {
801            // Get the calling classloader
802            ClassLoader cl = VMStackWalker.getCallingClassLoader();
803            if (cl != null && !cl.isAncestorOf(contextClassLoader))
804              sm.checkPermission(new RuntimePermission("getClassLoader"));
805          }
806        return contextClassLoader;
807      }
808    
809      /**
810       * Sets the context classloader for this Thread. When not explicitly set,
811       * the context classloader for a thread is the same as the context
812       * classloader of the thread that created this thread. The first thread has
813       * as context classloader the system classloader. There may be a security
814       * check for <code>RuntimePermission("setContextClassLoader")</code>.
815       *
816       * @param classloader the new context class loader
817       * @throws SecurityException when permission is denied
818       * @see #getContextClassLoader()
819       * @since 1.2
820       */
821      public synchronized void setContextClassLoader(ClassLoader classloader)
822      {
823        SecurityManager sm = System.getSecurityManager();
824        if (sm != null)
825          sm.checkPermission(new RuntimePermission("setContextClassLoader"));
826        this.contextClassLoader = classloader;
827      }
828    
829      /**
830       * Set this Thread's name.  There may be a security check,
831       * <code>checkAccess</code>.
832       *
833       * @param name the new name for this Thread
834       * @throws NullPointerException if name is null
835       * @throws SecurityException if you cannot modify this Thread
836       */
837      public final void setName(String name)
838      {
839        checkAccess();
840        // The Class Libraries book says ``threadName cannot be null''.  I
841        // take this to mean NullPointerException.
842        if (name == null)
843          throw new NullPointerException();
844        this.name = name;
845      }
846    
847      /**
848       * Yield to another thread. The Thread will not lose any locks it holds
849       * during this time. There are no guarantees which thread will be
850       * next to run, and it could even be this one, but most VMs will choose
851       * the highest priority thread that has been waiting longest.
852       */
853      public static native void yield();
854    
855      /**
856       * Suspend the current Thread's execution for the specified amount of
857       * time. The Thread will not lose any locks it has during this time. There
858       * are no guarantees which thread will be next to run, but most VMs will
859       * choose the highest priority thread that has been waiting longest.
860       *
861       * @param ms the number of milliseconds to sleep, or 0 for forever
862       * @throws InterruptedException if the Thread is (or was) interrupted;
863       *         it's <i>interrupted status</i> will be cleared
864       * @throws IllegalArgumentException if ms is negative
865       * @see #interrupt()
866       * @see #notify()
867       * @see #wait(long)
868       */
869      public static void sleep(long ms) throws InterruptedException
870      {
871        sleep(ms, 0);
872      }
873    
874      /**
875       * Suspend the current Thread's execution for the specified amount of
876       * time. The Thread will not lose any locks it has during this time. There
877       * are no guarantees which thread will be next to run, but most VMs will
878       * choose the highest priority thread that has been waiting longest.
879       * <p>
880       * Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs
881       * do not offer that fine a grain of timing resolution. When ms is
882       * zero and ns is non-zero the Thread will sleep for at least one
883       * milli second. There is no guarantee that this thread can start up
884       * immediately when time expires, because some other thread may be
885       * active.  So don't expect real-time performance.
886       *
887       * @param ms the number of milliseconds to sleep, or 0 for forever
888       * @param ns the number of extra nanoseconds to sleep (0-999999)
889       * @throws InterruptedException if the Thread is (or was) interrupted;
890       *         it's <i>interrupted status</i> will be cleared
891       * @throws IllegalArgumentException if ms or ns is negative
892       *         or ns is larger than 999999.
893       * @see #interrupt()
894       * @see #notify()
895       * @see #wait(long, int)
896       */
897      public static native void sleep(long timeout, int nanos)
898        throws InterruptedException;
899    
900      /**
901       * Start this Thread, calling the run() method of the Runnable this Thread
902       * was created with, or else the run() method of the Thread itself. This
903       * is the only way to start a new thread; calling run by yourself will just
904       * stay in the same thread. The virtual machine will remove the thread from
905       * its thread group when the run() method completes.
906       *
907       * @throws IllegalThreadStateException if the thread has already started
908       * @see #run()
909       */
910      public native void start();
911    
912      /**
913       * Cause this Thread to stop abnormally because of the throw of a ThreadDeath
914       * error. If you stop a Thread that has not yet started, it will stop
915       * immediately when it is actually started.
916       *
917       * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
918       * leave data in bad states.  Hence, there is a security check:
919       * <code>checkAccess(this)</code>, plus another one if the current thread
920       * is not this: <code>RuntimePermission("stopThread")</code>. If you must
921       * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
922       * ThreadDeath is the only exception which does not print a stack trace when
923       * the thread dies.
924       *
925       * @throws SecurityException if you cannot stop the Thread
926       * @see #interrupt()
927       * @see #checkAccess()
928       * @see #start()
929       * @see ThreadDeath
930       * @see ThreadGroup#uncaughtException(Thread, Throwable)
931       * @see SecurityManager#checkAccess(Thread)
932       * @see SecurityManager#checkPermission(Permission)
933       * @deprecated unsafe operation, try not to use
934       */
935      public final void stop()
936      {
937        // Argument doesn't matter, because this is no longer
938        // supported.
939        stop(null);
940      }
941    
942      /**
943       * Cause this Thread to stop abnormally and throw the specified exception.
944       * If you stop a Thread that has not yet started, the stop is ignored
945       * (contrary to what the JDK documentation says).
946       * <b>WARNING</b>This bypasses Java security, and can throw a checked
947       * exception which the call stack is unprepared to handle. Do not abuse
948       * this power.
949       *
950       * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
951       * leave data in bad states.  Hence, there is a security check:
952       * <code>checkAccess(this)</code>, plus another one if the current thread
953       * is not this: <code>RuntimePermission("stopThread")</code>. If you must
954       * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
955       * ThreadDeath is the only exception which does not print a stack trace when
956       * the thread dies.
957       *
958       * @param t the Throwable to throw when the Thread dies
959       * @throws SecurityException if you cannot stop the Thread
960       * @throws NullPointerException in the calling thread, if t is null
961       * @see #interrupt()
962       * @see #checkAccess()
963       * @see #start()
964       * @see ThreadDeath
965       * @see ThreadGroup#uncaughtException(Thread, Throwable)
966       * @see SecurityManager#checkAccess(Thread)
967       * @see SecurityManager#checkPermission(Permission)
968       * @deprecated unsafe operation, try not to use
969       */
970      public final native void stop(Throwable t);
971    
972      /**
973       * Suspend this Thread.  It will not come back, ever, unless it is resumed.
974       *
975       * <p>This is inherently unsafe, as the suspended thread still holds locks,
976       * and can potentially deadlock your program.  Hence, there is a security
977       * check: <code>checkAccess</code>.
978       *
979       * @throws SecurityException if you cannot suspend the Thread
980       * @see #checkAccess()
981       * @see #resume()
982       * @deprecated unsafe operation, try not to use
983       */
984      public final native void suspend();
985    
986      /**
987       * Set this Thread's priority. There may be a security check,
988       * <code>checkAccess</code>, then the priority is set to the smaller of
989       * priority and the ThreadGroup maximum priority.
990       *
991       * @param priority the new priority for this Thread
992       * @throws IllegalArgumentException if priority exceeds MIN_PRIORITY or
993       *         MAX_PRIORITY
994       * @throws SecurityException if you cannot modify this Thread
995       * @see #getPriority()
996       * @see #checkAccess()
997       * @see ThreadGroup#getMaxPriority()
998       * @see #MIN_PRIORITY
999       * @see #MAX_PRIORITY
1000       */
1001      public final native void setPriority(int newPriority);
1002    
1003      /**
1004       * Returns a string representation of this thread, including the
1005       * thread's name, priority, and thread group.
1006       *
1007       * @return a human-readable String representing this Thread
1008       */
1009      public String toString()
1010      {
1011        return ("Thread[" + name + "," + priority + ","
1012                + (group == null ? "" : group.getName()) + "]");
1013      }
1014    
1015      private final native void initialize_native();
1016    
1017      private final native static String gen_name();
1018    
1019      /**
1020       * Returns the map used by ThreadLocal to store the thread local values.
1021       */
1022      static Map getThreadLocals()
1023      {
1024        Thread thread = currentThread();
1025        Map locals = thread.locals;
1026        if (locals == null)
1027          {
1028            locals = thread.locals = new WeakIdentityHashMap();
1029          }
1030        return locals;
1031      }
1032    
1033      /** 
1034       * Assigns the given <code>UncaughtExceptionHandler</code> to this
1035       * thread.  This will then be called if the thread terminates due
1036       * to an uncaught exception, pre-empting that of the
1037       * <code>ThreadGroup</code>.
1038       *
1039       * @param h the handler to use for this thread.
1040       * @throws SecurityException if the current thread can't modify this thread.
1041       * @since 1.5 
1042       */
1043      public void setUncaughtExceptionHandler(UncaughtExceptionHandler h)
1044      {
1045        SecurityManager sm = SecurityManager.current; // Be thread-safe.
1046        if (sm != null)
1047          sm.checkAccess(this);    
1048        exceptionHandler = h;
1049      }
1050    
1051      /** 
1052       * <p>
1053       * Returns the handler used when this thread terminates due to an
1054       * uncaught exception.  The handler used is determined by the following:
1055       * </p>
1056       * <ul>
1057       * <li>If this thread has its own handler, this is returned.</li>
1058       * <li>If not, then the handler of the thread's <code>ThreadGroup</code>
1059       * object is returned.</li>
1060       * <li>If both are unavailable, then <code>null</code> is returned
1061       *     (which can only happen when the thread was terminated since
1062       *      then it won't have an associated thread group anymore).</li>
1063       * </ul>
1064       * 
1065       * @return the appropriate <code>UncaughtExceptionHandler</code> or
1066       *         <code>null</code> if one can't be obtained.
1067       * @since 1.5 
1068       */
1069      public UncaughtExceptionHandler getUncaughtExceptionHandler()
1070      {
1071        // FIXME: if thread is dead, should return null...
1072        return exceptionHandler != null ? exceptionHandler : group;
1073      }
1074    
1075      /** 
1076       * <p>
1077       * Sets the default uncaught exception handler used when one isn't
1078       * provided by the thread or its associated <code>ThreadGroup</code>.
1079       * This exception handler is used when the thread itself does not
1080       * have an exception handler, and the thread's <code>ThreadGroup</code>
1081       * does not override this default mechanism with its own.  As the group
1082       * calls this handler by default, this exception handler should not defer
1083       * to that of the group, as it may lead to infinite recursion.
1084       * </p>
1085       * <p>
1086       * Uncaught exception handlers are used when a thread terminates due to
1087       * an uncaught exception.  Replacing this handler allows default code to
1088       * be put in place for all threads in order to handle this eventuality.
1089       * </p>
1090       *
1091       * @param h the new default uncaught exception handler to use.
1092       * @throws SecurityException if a security manager is present and
1093       *                           disallows the runtime permission
1094       *                           "setDefaultUncaughtExceptionHandler".
1095       * @since 1.5 
1096       */
1097      public static void 
1098        setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler h)
1099      {
1100        SecurityManager sm = SecurityManager.current; // Be thread-safe.
1101        if (sm != null)
1102          sm.checkPermission(new RuntimePermission("setDefaultUncaughtExceptionHandler"));    
1103        defaultHandler = h;
1104      }
1105    
1106      /** 
1107       * Returns the handler used by default when a thread terminates
1108       * unexpectedly due to an exception, or <code>null</code> if one doesn't
1109       * exist.
1110       *
1111       * @return the default uncaught exception handler.
1112       * @since 1.5 
1113       */
1114      public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
1115      {
1116        return defaultHandler;
1117      }
1118      
1119      /** 
1120       * Returns the unique identifier for this thread.  This ID is generated
1121       * on thread creation, and may be re-used on its death.
1122       *
1123       * @return a positive long number representing the thread's ID.
1124       * @since 1.5 
1125       */
1126      public long getId()
1127      {
1128        return threadId;
1129      }
1130    
1131      /**
1132       * <p>
1133       * This interface is used to handle uncaught exceptions
1134       * which cause a <code>Thread</code> to terminate.  When
1135       * a thread, t, is about to terminate due to an uncaught
1136       * exception, the virtual machine looks for a class which
1137       * implements this interface, in order to supply it with
1138       * the dying thread and its uncaught exception.
1139       * </p>
1140       * <p>
1141       * The virtual machine makes two attempts to find an
1142       * appropriate handler for the uncaught exception, in
1143       * the following order:
1144       * </p>
1145       * <ol>
1146       * <li>
1147       * <code>t.getUncaughtExceptionHandler()</code> --
1148       * the dying thread is queried first for a handler
1149       * specific to that thread.
1150       * </li>
1151       * <li>
1152       * <code>t.getThreadGroup()</code> --
1153       * the thread group of the dying thread is used to
1154       * handle the exception.  If the thread group has
1155       * no special requirements for handling the exception,
1156       * it may simply forward it on to
1157       * <code>Thread.getDefaultUncaughtExceptionHandler()</code>,
1158       * the default handler, which is used as a last resort.
1159       * </li>
1160       * </ol>
1161       * <p>
1162       * The first handler found is the one used to handle
1163       * the uncaught exception.
1164       * </p>
1165       *
1166       * @author Tom Tromey <tromey@redhat.com>
1167       * @author Andrew John Hughes <gnu_andrew@member.fsf.org>
1168       * @since 1.5
1169       * @see Thread#getUncaughtExceptionHandler()
1170       * @see Thread#setUncaughtExceptionHandler(UncaughtExceptionHandler)
1171       * @see Thread#getDefaultUncaughtExceptionHandler()
1172       * @see
1173       * Thread#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)
1174       */
1175      public interface UncaughtExceptionHandler
1176      {
1177        /**
1178         * Invoked by the virtual machine with the dying thread
1179         * and the uncaught exception.  Any exceptions thrown
1180         * by this method are simply ignored by the virtual
1181         * machine.
1182         *
1183         * @param thr the dying thread.
1184         * @param exc the uncaught exception.
1185         */
1186        void uncaughtException(Thread thr, Throwable exc);
1187      }
1188    
1189      /** 
1190       * <p>
1191       * Represents the current state of a thread, according to the VM rather
1192       * than the operating system.  It can be one of the following:
1193       * </p>
1194       * <ul>
1195       * <li>NEW -- The thread has just been created but is not yet running.</li>
1196       * <li>RUNNABLE -- The thread is currently running or can be scheduled
1197       * to run.</li>
1198       * <li>BLOCKED -- The thread is blocked waiting on an I/O operation
1199       * or to obtain a lock.</li>
1200       * <li>WAITING -- The thread is waiting indefinitely for another thread
1201       * to do something.</li>
1202       * <li>TIMED_WAITING -- The thread is waiting for a specific amount of time
1203       * for another thread to do something.</li>
1204       * <li>TERMINATED -- The thread has exited.</li>
1205       * </ul>
1206       *
1207       * @since 1.5 
1208       */
1209      public enum State
1210      {
1211        BLOCKED, NEW, RUNNABLE, TERMINATED, TIMED_WAITING, WAITING;
1212      }
1213    
1214    
1215      /**
1216       * Returns the current state of the thread.  This
1217       * is designed for monitoring thread behaviour, rather
1218       * than for synchronization control.
1219       *
1220       * @return the current thread state.
1221       */
1222      public native State getState();
1223    
1224      /**
1225       * <p>
1226       * Returns a map of threads to stack traces for each
1227       * live thread.  The keys of the map are {@link Thread}
1228       * objects, which map to arrays of {@link StackTraceElement}s.
1229       * The results obtained from Calling this method are
1230       * equivalent to calling {@link getStackTrace()} on each
1231       * thread in succession.  Threads may be executing while
1232       * this takes place, and the results represent a snapshot
1233       * of the thread at the time its {@link getStackTrace()}
1234       * method is called.
1235       * </p>
1236       * <p>
1237       * The stack trace information contains the methods called
1238       * by the thread, with the most recent method forming the
1239       * first element in the array.  The array will be empty
1240       * if the virtual machine can not obtain information on the
1241       * thread. 
1242       * </p>
1243       * <p>
1244       * To execute this method, the current security manager
1245       * (if one exists) must allow both the
1246       * <code>"getStackTrace"</code> and
1247       * <code>"modifyThreadGroup"</code> {@link RuntimePermission}s.
1248       * </p>
1249       * 
1250       * @return a map of threads to arrays of {@link StackTraceElement}s.
1251       * @throws SecurityException if a security manager exists, and
1252       *                           prevents either or both the runtime
1253       *                           permissions specified above.
1254       * @since 1.5
1255       * @see #getStackTrace()
1256       */
1257      public static Map<Thread, StackTraceElement[]> getAllStackTraces()
1258      {
1259        ThreadGroup group = currentThread().group;
1260        while (group.getParent() != null)
1261          group = group.getParent();
1262        int arraySize = group.activeCount();
1263        Thread[] threadList = new Thread[arraySize];
1264        int filled = group.enumerate(threadList);
1265        while (filled == arraySize)
1266          {
1267            arraySize *= 2;
1268            threadList = new Thread[arraySize];
1269            filled = group.enumerate(threadList);
1270          }
1271        Map traces = new HashMap();
1272        for (int a = 0; a < filled; ++a)
1273          traces.put(threadList[a],
1274                     threadList[a].getStackTrace());
1275        return traces;
1276      }
1277    
1278      /**
1279       * <p>
1280       * Returns an array of {@link StackTraceElement}s
1281       * representing the current stack trace of this thread.
1282       * The first element of the array is the most recent
1283       * method called, and represents the top of the stack.
1284       * The elements continue in this order, with the last
1285       * element representing the bottom of the stack.
1286       * </p>
1287       * <p>
1288       * A zero element array is returned for threads which
1289       * have not yet started (and thus have not yet executed
1290       * any methods) or for those which have terminated.
1291       * Where the virtual machine can not obtain a trace for
1292       * the thread, an empty array is also returned.  The
1293       * virtual machine may also omit some methods from the
1294       * trace in non-zero arrays.
1295       * </p>
1296       * <p>
1297       * To execute this method, the current security manager
1298       * (if one exists) must allow both the
1299       * <code>"getStackTrace"</code> and
1300       * <code>"modifyThreadGroup"</code> {@link RuntimePermission}s.
1301       * </p>
1302       *
1303       * @return a stack trace for this thread.
1304       * @throws SecurityException if a security manager exists, and
1305       *                           prevents the use of the
1306       *                           <code>"getStackTrace"</code>
1307       *                           permission.
1308       * @since 1.5
1309       * @see #getAllStackTraces()
1310       */
1311      public StackTraceElement[] getStackTrace()
1312      {
1313        SecurityManager sm = SecurityManager.current; // Be thread-safe.
1314        if (sm != null)
1315          sm.checkPermission(new RuntimePermission("getStackTrace"));
1316    
1317        // Calling java.lang.management via reflection means that
1318        // javax.management be overridden in the endorsed directory.
1319    
1320        // This is the equivalent code:
1321        //
1322        //     ThreadMXBean bean = ManagementFactory.getThreadMXBean();
1323        //     ThreadInfo info = bean.getThreadInfo(getId(), Integer.MAX_VALUE);
1324        //     return info.getStackTrace();
1325    
1326        try
1327          {
1328            try
1329              {
1330                Object bean 
1331                  = (Class.forName("java.lang.management.ManagementFactory")
1332                     .getDeclaredMethod("getThreadMXBean")
1333                     .invoke(null));
1334                Object info = bean.getClass()
1335                  .getDeclaredMethod("getThreadInfo", long.class, int.class)
1336                  .invoke(bean, new Long(getId()), new Integer(Integer.MAX_VALUE));
1337                Object trace = info.getClass()
1338                  .getDeclaredMethod("getStackTrace").invoke(info);
1339                return (StackTraceElement[])trace;
1340              }
1341            catch (InvocationTargetException e)
1342              {
1343                throw (Exception)e.getTargetException();
1344              }
1345          }
1346        catch (UnsupportedOperationException e)
1347          {
1348            throw e;
1349          }
1350        catch (Exception e)
1351          {
1352            throw new UnsupportedOperationException(e);
1353          }
1354      }
1355    }