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