Source for java.lang.Thread

   1: /* Thread -- an independent thread of executable code
   2:    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
   3:    Free Software Foundation
   4: 
   5: This file is part of GNU Classpath.
   6: 
   7: GNU Classpath is free software; you can redistribute it and/or modify
   8: it under the terms of the GNU General Public License as published by
   9: the Free Software Foundation; either version 2, or (at your option)
  10: any later version.
  11: 
  12: GNU Classpath is distributed in the hope that it will be useful, but
  13: WITHOUT ANY WARRANTY; without even the implied warranty of
  14: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15: General Public License for more details.
  16: 
  17: You should have received a copy of the GNU General Public License
  18: along with GNU Classpath; see the file COPYING.  If not, write to the
  19: Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  20: 02110-1301 USA.
  21: 
  22: Linking this library statically or dynamically with other modules is
  23: making a combined work based on this library.  Thus, the terms and
  24: conditions of the GNU General Public License cover the whole
  25: combination.
  26: 
  27: As a special exception, the copyright holders of this library give you
  28: permission to link this library with independent modules to produce an
  29: executable, regardless of the license terms of these independent
  30: modules, and to copy and distribute the resulting executable under
  31: terms of your choice, provided that you also meet, for each linked
  32: independent module, the terms and conditions of the license of that
  33: module.  An independent module is a module which is not derived from
  34: or based on this library.  If you modify this library, you may extend
  35: this exception to your version of the library, but you are not
  36: obligated to do so.  If you do not wish to do so, delete this
  37: exception statement from your version. */
  38: 
  39: package java.lang;
  40: 
  41: import gnu.classpath.VMStackWalker;
  42: import gnu.java.util.WeakIdentityHashMap;
  43: 
  44: import java.lang.management.ManagementFactory;
  45: import java.lang.management.ThreadInfo;
  46: import java.lang.management.ThreadMXBean;
  47: 
  48: import java.security.Permission;
  49: 
  50: import java.util.HashMap;
  51: import java.util.Map;
  52: 
  53: /* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3
  54:  * "The Java Language Specification", ISBN 0-201-63451-1
  55:  * plus online API docs for JDK 1.2 beta from http://www.javasoft.com.
  56:  * Status:  Believed complete to version 1.4, with caveats. We do not
  57:  *          implement the deprecated (and dangerous) stop, suspend, and resume
  58:  *          methods. Security implementation is not complete.
  59:  */
  60: 
  61: /**
  62:  * Thread represents a single thread of execution in the VM. When an
  63:  * application VM starts up, it creates a non-daemon Thread which calls the
  64:  * main() method of a particular class.  There may be other Threads running,
  65:  * such as the garbage collection thread.
  66:  *
  67:  * <p>Threads have names to identify them.  These names are not necessarily
  68:  * unique. Every Thread has a priority, as well, which tells the VM which
  69:  * Threads should get more running time. New threads inherit the priority
  70:  * and daemon status of the parent thread, by default.
  71:  *
  72:  * <p>There are two methods of creating a Thread: you may subclass Thread and
  73:  * implement the <code>run()</code> method, at which point you may start the
  74:  * Thread by calling its <code>start()</code> method, or you may implement
  75:  * <code>Runnable</code> in the class you want to use and then call new
  76:  * <code>Thread(your_obj).start()</code>.
  77:  *
  78:  * <p>The virtual machine runs until all non-daemon threads have died (either
  79:  * by returning from the run() method as invoked by start(), or by throwing
  80:  * an uncaught exception); or until <code>System.exit</code> is called with
  81:  * adequate permissions.
  82:  *
  83:  * <p>It is unclear at what point a Thread should be added to a ThreadGroup,
  84:  * and at what point it should be removed. Should it be inserted when it
  85:  * starts, or when it is created?  Should it be removed when it is suspended
  86:  * or interrupted?  The only thing that is clear is that the Thread should be
  87:  * removed when it is stopped.
  88:  *
  89:  * @author Tom Tromey
  90:  * @author John Keiser
  91:  * @author Eric Blake (ebb9@email.byu.edu)
  92:  * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  93:  * @see Runnable
  94:  * @see Runtime#exit(int)
  95:  * @see #run()
  96:  * @see #start()
  97:  * @see ThreadLocal
  98:  * @since 1.0
  99:  * @status updated to 1.4
 100:  */
 101: public 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:   WeakIdentityHashMap 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:     
 371:     synchronized (Thread.class)
 372:       {
 373:         this.threadId = ++totalThreadsCreated;
 374:       }
 375: 
 376:     priority = current.priority;
 377:     daemon = current.daemon;
 378:     contextClassLoader = current.contextClassLoader;
 379:     contextClassLoaderIsSystemClassLoader =
 380:         current.contextClassLoaderIsSystemClassLoader;
 381: 
 382:     group.addThread(this);
 383:     InheritableThreadLocal.newChildThread(this);
 384:   }
 385: 
 386:   /**
 387:    * Used by the VM to create thread objects for threads started outside
 388:    * of Java. Note: caller is responsible for adding the thread to
 389:    * a group and InheritableThreadLocal.
 390:    * Note: This constructor should not call any methods that could result
 391:    * in a call to Thread.currentThread(), because that makes life harder
 392:    * for the VM.
 393:    *
 394:    * @param vmThread the native thread
 395:    * @param name the thread name or null to use the default naming scheme
 396:    * @param priority current priority
 397:    * @param daemon is the thread a background thread?
 398:    */
 399:   Thread(VMThread vmThread, String name, int priority, boolean daemon)
 400:   {
 401:     this.vmThread = vmThread;
 402:     this.runnable = null;
 403:     if (name == null)
 404:       name = createAnonymousThreadName();
 405:     this.name = name;
 406:     this.priority = priority;
 407:     this.daemon = daemon;
 408:     // By default the context class loader is the system class loader,
 409:     // we set a flag to signal this because we don't want to call
 410:     // ClassLoader.getSystemClassLoader() at this point, because on
 411:     // VMs that lazily create the system class loader that might result
 412:     // in running user code (when a custom system class loader is specified)
 413:     // and that user code could call Thread.currentThread().
 414:     // ClassLoader.getSystemClassLoader() can also return null, if the system
 415:     // is currently in the process of constructing the system class loader
 416:     // (and, as above, the constructiong sequence calls Thread.currenThread()).
 417:     contextClassLoaderIsSystemClassLoader = true;
 418:     synchronized (Thread.class)
 419:     {
 420:       this.threadId = ++totalThreadsCreated;
 421:     }
 422:   }
 423:   
 424:   /**
 425:    * Generate a name for an anonymous thread.
 426:    */
 427:   private static synchronized String createAnonymousThreadName()
 428:   {
 429:     return "Thread-" + ++numAnonymousThreadsCreated;
 430:   }
 431: 
 432:   /**
 433:    * Get the number of active threads in the current Thread's ThreadGroup.
 434:    * This implementation calls
 435:    * <code>currentThread().getThreadGroup().activeCount()</code>.
 436:    *
 437:    * @return the number of active threads in the current ThreadGroup
 438:    * @see ThreadGroup#activeCount()
 439:    */
 440:   public static int activeCount()
 441:   {
 442:     return currentThread().group.activeCount();
 443:   }
 444: 
 445:   /**
 446:    * Check whether the current Thread is allowed to modify this Thread. This
 447:    * passes the check on to <code>SecurityManager.checkAccess(this)</code>.
 448:    *
 449:    * @throws SecurityException if the current Thread cannot modify this Thread
 450:    * @see SecurityManager#checkAccess(Thread)
 451:    */
 452:   public final void checkAccess()
 453:   {
 454:     // Bypass System.getSecurityManager, for bootstrap efficiency.
 455:     SecurityManager sm = SecurityManager.current;
 456:     if (sm != null)
 457:       sm.checkAccess(this);
 458:   }
 459: 
 460:   /**
 461:    * Count the number of stack frames in this Thread.  The Thread in question
 462:    * must be suspended when this occurs.
 463:    *
 464:    * @return the number of stack frames in this Thread
 465:    * @throws IllegalThreadStateException if this Thread is not suspended
 466:    * @deprecated pointless, since suspend is deprecated
 467:    */
 468:   public int countStackFrames()
 469:   {
 470:     VMThread t = vmThread;
 471:     if (t == null || group == null)
 472:       throw new IllegalThreadStateException();
 473: 
 474:     return t.countStackFrames();
 475:   }
 476: 
 477:   /**
 478:    * Get the currently executing Thread. In the situation that the
 479:    * currently running thread was created by native code and doesn't
 480:    * have an associated Thread object yet, a new Thread object is
 481:    * constructed and associated with the native thread.
 482:    *
 483:    * @return the currently executing Thread
 484:    */
 485:   public static Thread currentThread()
 486:   {
 487:     return VMThread.currentThread();
 488:   }
 489: 
 490:   /**
 491:    * Originally intended to destroy this thread, this method was never
 492:    * implemented by Sun, and is hence a no-op.
 493:    *
 494:    * @deprecated This method was originally intended to simply destroy
 495:    *             the thread without performing any form of cleanup operation.
 496:    *             However, it was never implemented.  It is now deprecated
 497:    *             for the same reason as <code>suspend()</code>,
 498:    *             <code>stop()</code> and <code>resume()</code>; namely,
 499:    *             it is prone to deadlocks.  If a thread is destroyed while
 500:    *             it still maintains a lock on a resource, then this resource
 501:    *             will remain locked and any attempts by other threads to
 502:    *             access the resource will result in a deadlock.  Thus, even
 503:    *             an implemented version of this method would be still be
 504:    *             deprecated, due to its unsafe nature.
 505:    * @throws NoSuchMethodError as this method was never implemented.
 506:    */
 507:   public void destroy()
 508:   {
 509:     throw new NoSuchMethodError();
 510:   }
 511:   
 512:   /**
 513:    * Print a stack trace of the current thread to stderr using the same
 514:    * format as Throwable's printStackTrace() method.
 515:    *
 516:    * @see Throwable#printStackTrace()
 517:    */
 518:   public static void dumpStack()
 519:   {
 520:     new Throwable().printStackTrace();
 521:   }
 522: 
 523:   /**
 524:    * Copy every active thread in the current Thread's ThreadGroup into the
 525:    * array. Extra threads are silently ignored. This implementation calls
 526:    * <code>getThreadGroup().enumerate(array)</code>, which may have a
 527:    * security check, <code>checkAccess(group)</code>.
 528:    *
 529:    * @param array the array to place the Threads into
 530:    * @return the number of Threads placed into the array
 531:    * @throws NullPointerException if array is null
 532:    * @throws SecurityException if you cannot access the ThreadGroup
 533:    * @see ThreadGroup#enumerate(Thread[])
 534:    * @see #activeCount()
 535:    * @see SecurityManager#checkAccess(ThreadGroup)
 536:    */
 537:   public static int enumerate(Thread[] array)
 538:   {
 539:     return currentThread().group.enumerate(array);
 540:   }
 541:   
 542:   /**
 543:    * Get this Thread's name.
 544:    *
 545:    * @return this Thread's name
 546:    */
 547:   public final String getName()
 548:   {
 549:     VMThread t = vmThread;
 550:     return t == null ? name : t.getName();
 551:   }
 552: 
 553:   /**
 554:    * Get this Thread's priority.
 555:    *
 556:    * @return the Thread's priority
 557:    */
 558:   public final synchronized int getPriority()
 559:   {
 560:     VMThread t = vmThread;
 561:     return t == null ? priority : t.getPriority();
 562:   }
 563: 
 564:   /**
 565:    * Get the ThreadGroup this Thread belongs to. If the thread has died, this
 566:    * returns null.
 567:    *
 568:    * @return this Thread's ThreadGroup
 569:    */
 570:   public final ThreadGroup getThreadGroup()
 571:   {
 572:     return group;
 573:   }
 574: 
 575:   /**
 576:    * Checks whether the current thread holds the monitor on a given object.
 577:    * This allows you to do <code>assert Thread.holdsLock(obj)</code>.
 578:    *
 579:    * @param obj the object to test lock ownership on.
 580:    * @return true if the current thread is currently synchronized on obj
 581:    * @throws NullPointerException if obj is null
 582:    * @since 1.4
 583:    */
 584:   public static boolean holdsLock(Object obj)
 585:   {
 586:     return VMThread.holdsLock(obj);
 587:   }
 588: 
 589:   /**
 590:    * Interrupt this Thread. First, there is a security check,
 591:    * <code>checkAccess</code>. Then, depending on the current state of the
 592:    * thread, various actions take place:
 593:    *
 594:    * <p>If the thread is waiting because of {@link #wait()},
 595:    * {@link #sleep(long)}, or {@link #join()}, its <i>interrupt status</i>
 596:    * will be cleared, and an InterruptedException will be thrown. Notice that
 597:    * this case is only possible if an external thread called interrupt().
 598:    *
 599:    * <p>If the thread is blocked in an interruptible I/O operation, in
 600:    * {@link java.nio.channels.InterruptibleChannel}, the <i>interrupt
 601:    * status</i> will be set, and ClosedByInterruptException will be thrown.
 602:    *
 603:    * <p>If the thread is blocked on a {@link java.nio.channels.Selector}, the
 604:    * <i>interrupt status</i> will be set, and the selection will return, with
 605:    * a possible non-zero value, as though by the wakeup() method.
 606:    *
 607:    * <p>Otherwise, the interrupt status will be set.
 608:    *
 609:    * @throws SecurityException if you cannot modify this Thread
 610:    */
 611:   public synchronized void interrupt()
 612:   {
 613:     checkAccess();
 614:     VMThread t = vmThread;
 615:     if (t != null)
 616:       t.interrupt();
 617:   }
 618: 
 619:   /**
 620:    * Determine whether the current Thread has been interrupted, and clear
 621:    * the <i>interrupted status</i> in the process.
 622:    *
 623:    * @return whether the current Thread has been interrupted
 624:    * @see #isInterrupted()
 625:    */
 626:   public static boolean interrupted()
 627:   {
 628:     return VMThread.interrupted();
 629:   }
 630: 
 631:   /**
 632:    * Determine whether the given Thread has been interrupted, but leave
 633:    * the <i>interrupted status</i> alone in the process.
 634:    *
 635:    * @return whether the Thread has been interrupted
 636:    * @see #interrupted()
 637:    */
 638:   public boolean isInterrupted()
 639:   {
 640:     VMThread t = vmThread;
 641:     return t != null && t.isInterrupted();
 642:   }
 643: 
 644:   /**
 645:    * Determine whether this Thread is alive. A thread which is alive has
 646:    * started and not yet died.
 647:    *
 648:    * @return whether this Thread is alive
 649:    */
 650:   public final boolean isAlive()
 651:   {
 652:     return vmThread != null && group != null;
 653:   }
 654: 
 655:   /**
 656:    * Tell whether this is a daemon Thread or not.
 657:    *
 658:    * @return whether this is a daemon Thread or not
 659:    * @see #setDaemon(boolean)
 660:    */
 661:   public final boolean isDaemon()
 662:   {
 663:     VMThread t = vmThread;
 664:     return t == null ? daemon : t.isDaemon();
 665:   }
 666: 
 667:   /**
 668:    * Wait forever for the Thread in question to die.
 669:    *
 670:    * @throws InterruptedException if the Thread is interrupted; it's
 671:    *         <i>interrupted status</i> will be cleared
 672:    */
 673:   public final void join() throws InterruptedException
 674:   {
 675:     join(0, 0);
 676:   }
 677: 
 678:   /**
 679:    * Wait the specified amount of time for the Thread in question to die.
 680:    *
 681:    * @param ms the number of milliseconds to wait, or 0 for forever
 682:    * @throws InterruptedException if the Thread is interrupted; it's
 683:    *         <i>interrupted status</i> will be cleared
 684:    */
 685:   public final void join(long ms) throws InterruptedException
 686:   {
 687:     join(ms, 0);
 688:   }
 689: 
 690:   /**
 691:    * Wait the specified amount of time for the Thread in question to die.
 692:    *
 693:    * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
 694:    * not offer that fine a grain of timing resolution. Besides, there is
 695:    * no guarantee that this thread can start up immediately when time expires,
 696:    * because some other thread may be active.  So don't expect real-time
 697:    * performance.
 698:    *
 699:    * @param ms the number of milliseconds to wait, or 0 for forever
 700:    * @param ns the number of extra nanoseconds to sleep (0-999999)
 701:    * @throws InterruptedException if the Thread is interrupted; it's
 702:    *         <i>interrupted status</i> will be cleared
 703:    * @throws IllegalArgumentException if ns is invalid
 704:    */
 705:   public final void join(long ms, int ns) throws InterruptedException
 706:   {
 707:     if (ms < 0 || ns < 0 || ns > 999999)
 708:       throw new IllegalArgumentException();
 709: 
 710:     VMThread t = vmThread;
 711:     if (t != null)
 712:       t.join(ms, ns);
 713:   }
 714: 
 715:   /**
 716:    * Resume this Thread.  If the thread is not suspended, this method does
 717:    * nothing. To mirror suspend(), there may be a security check:
 718:    * <code>checkAccess</code>.
 719:    *
 720:    * @throws SecurityException if you cannot resume the Thread
 721:    * @see #checkAccess()
 722:    * @see #suspend()
 723:    * @deprecated pointless, since suspend is deprecated
 724:    */
 725:   public final synchronized void resume()
 726:   {
 727:     checkAccess();
 728:     VMThread t = vmThread;
 729:     if (t != null)
 730:       t.resume();
 731:   }
 732:   
 733:   /**
 734:    * The method of Thread that will be run if there is no Runnable object
 735:    * associated with the Thread. Thread's implementation does nothing at all.
 736:    *
 737:    * @see #start()
 738:    * @see #Thread(ThreadGroup, Runnable, String)
 739:    */
 740:   public void run()
 741:   {
 742:     if (runnable != null)
 743:       runnable.run();
 744:   }
 745: 
 746:   /**
 747:    * Set the daemon status of this Thread.  If this is a daemon Thread, then
 748:    * the VM may exit even if it is still running.  This may only be called
 749:    * before the Thread starts running. There may be a security check,
 750:    * <code>checkAccess</code>.
 751:    *
 752:    * @param daemon whether this should be a daemon thread or not
 753:    * @throws SecurityException if you cannot modify this Thread
 754:    * @throws IllegalThreadStateException if the Thread is active
 755:    * @see #isDaemon()
 756:    * @see #checkAccess()
 757:    */
 758:   public final synchronized void setDaemon(boolean daemon)
 759:   {
 760:     if (vmThread != null)
 761:       throw new IllegalThreadStateException();
 762:     checkAccess();
 763:     this.daemon = daemon;
 764:   }
 765: 
 766:   /**
 767:    * Returns the context classloader of this Thread. The context
 768:    * classloader can be used by code that want to load classes depending
 769:    * on the current thread. Normally classes are loaded depending on
 770:    * the classloader of the current class. There may be a security check
 771:    * for <code>RuntimePermission("getClassLoader")</code> if the caller's
 772:    * class loader is not null or an ancestor of this thread's context class
 773:    * loader.
 774:    *
 775:    * @return the context class loader
 776:    * @throws SecurityException when permission is denied
 777:    * @see #setContextClassLoader(ClassLoader)
 778:    * @since 1.2
 779:    */
 780:   public synchronized ClassLoader getContextClassLoader()
 781:   {
 782:     ClassLoader loader = contextClassLoaderIsSystemClassLoader ?
 783:         ClassLoader.getSystemClassLoader() : contextClassLoader;
 784:     // Check if we may get the classloader
 785:     SecurityManager sm = SecurityManager.current;
 786:     if (loader != null && sm != null)
 787:       {
 788:         // Get the calling classloader
 789:     ClassLoader cl = VMStackWalker.getCallingClassLoader();
 790:         if (cl != null && !cl.isAncestorOf(loader))
 791:           sm.checkPermission(new RuntimePermission("getClassLoader"));
 792:       }
 793:     return loader;
 794:   }
 795: 
 796:   /**
 797:    * Sets the context classloader for this Thread. When not explicitly set,
 798:    * the context classloader for a thread is the same as the context
 799:    * classloader of the thread that created this thread. The first thread has
 800:    * as context classloader the system classloader. There may be a security
 801:    * check for <code>RuntimePermission("setContextClassLoader")</code>.
 802:    *
 803:    * @param classloader the new context class loader
 804:    * @throws SecurityException when permission is denied
 805:    * @see #getContextClassLoader()
 806:    * @since 1.2
 807:    */
 808:   public synchronized void setContextClassLoader(ClassLoader classloader)
 809:   {
 810:     SecurityManager sm = SecurityManager.current;
 811:     if (sm != null)
 812:       sm.checkPermission(new RuntimePermission("setContextClassLoader"));
 813:     this.contextClassLoader = classloader;
 814:     contextClassLoaderIsSystemClassLoader = false;
 815:   }
 816: 
 817:   /**
 818:    * Set this Thread's name.  There may be a security check,
 819:    * <code>checkAccess</code>.
 820:    *
 821:    * @param name the new name for this Thread
 822:    * @throws NullPointerException if name is null
 823:    * @throws SecurityException if you cannot modify this Thread
 824:    */
 825:   public final synchronized void setName(String name)
 826:   {
 827:     checkAccess();
 828:     // The Class Libraries book says ``threadName cannot be null''.  I
 829:     // take this to mean NullPointerException.
 830:     if (name == null)
 831:       throw new NullPointerException();
 832:     VMThread t = vmThread;
 833:     if (t != null)
 834:       t.setName(name);
 835:     else
 836:       this.name = name;
 837:   }
 838: 
 839:   /**
 840:    * Yield to another thread. The Thread will not lose any locks it holds
 841:    * during this time. There are no guarantees which thread will be
 842:    * next to run, and it could even be this one, but most VMs will choose
 843:    * the highest priority thread that has been waiting longest.
 844:    */
 845:   public static void yield()
 846:   {
 847:     VMThread.yield();
 848:   }
 849: 
 850:   /**
 851:    * Suspend the current Thread's execution for the specified amount of
 852:    * time. The Thread will not lose any locks it has during this time. There
 853:    * are no guarantees which thread will be next to run, but most VMs will
 854:    * choose the highest priority thread that has been waiting longest.
 855:    *
 856:    * @param ms the number of milliseconds to sleep, or 0 for forever
 857:    * @throws InterruptedException if the Thread is (or was) interrupted;
 858:    *         it's <i>interrupted status</i> will be cleared
 859:    * @throws IllegalArgumentException if ms is negative
 860:    * @see #interrupt()
 861:    * @see #notify()
 862:    * @see #wait(long)
 863:    */
 864:   public static void sleep(long ms) throws InterruptedException
 865:   {
 866:     sleep(ms, 0);
 867:   }
 868: 
 869:   /**
 870:    * Suspend the current Thread's execution for the specified amount of
 871:    * time. The Thread will not lose any locks it has during this time. There
 872:    * are no guarantees which thread will be next to run, but most VMs will
 873:    * choose the highest priority thread that has been waiting longest.
 874:    * <p>
 875:    * Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs
 876:    * do not offer that fine a grain of timing resolution. When ms is
 877:    * zero and ns is non-zero the Thread will sleep for at least one
 878:    * milli second. There is no guarantee that this thread can start up
 879:    * immediately when time expires, because some other thread may be
 880:    * active.  So don't expect real-time performance.
 881:    *
 882:    * @param ms the number of milliseconds to sleep, or 0 for forever
 883:    * @param ns the number of extra nanoseconds to sleep (0-999999)
 884:    * @throws InterruptedException if the Thread is (or was) interrupted;
 885:    *         it's <i>interrupted status</i> will be cleared
 886:    * @throws IllegalArgumentException if ms or ns is negative
 887:    *         or ns is larger than 999999.
 888:    * @see #interrupt()
 889:    * @see #notify()
 890:    * @see #wait(long, int)
 891:    */
 892:   public static void sleep(long ms, int ns) throws InterruptedException
 893:   {
 894:     // Check parameters
 895:     if (ms < 0 )
 896:       throw new IllegalArgumentException("Negative milliseconds: " + ms);
 897: 
 898:     if (ns < 0 || ns > 999999)
 899:       throw new IllegalArgumentException("Nanoseconds ouf of range: " + ns);
 900: 
 901:     // Really sleep
 902:     VMThread.sleep(ms, ns);
 903:   }
 904: 
 905:   /**
 906:    * Start this Thread, calling the run() method of the Runnable this Thread
 907:    * was created with, or else the run() method of the Thread itself. This
 908:    * is the only way to start a new thread; calling run by yourself will just
 909:    * stay in the same thread. The virtual machine will remove the thread from
 910:    * its thread group when the run() method completes.
 911:    *
 912:    * @throws IllegalThreadStateException if the thread has already started
 913:    * @see #run()
 914:    */
 915:   public synchronized void start()
 916:   {
 917:     if (vmThread != null || group == null)
 918:       throw new IllegalThreadStateException();
 919: 
 920:     VMThread.create(this, stacksize);
 921:   }
 922:   
 923:   /**
 924:    * Cause this Thread to stop abnormally because of the throw of a ThreadDeath
 925:    * error. If you stop a Thread that has not yet started, it will stop
 926:    * immediately when it is actually started.
 927:    *
 928:    * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
 929:    * leave data in bad states.  Hence, there is a security check:
 930:    * <code>checkAccess(this)</code>, plus another one if the current thread
 931:    * is not this: <code>RuntimePermission("stopThread")</code>. If you must
 932:    * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
 933:    * ThreadDeath is the only exception which does not print a stack trace when
 934:    * the thread dies.
 935:    *
 936:    * @throws SecurityException if you cannot stop the Thread
 937:    * @see #interrupt()
 938:    * @see #checkAccess()
 939:    * @see #start()
 940:    * @see ThreadDeath
 941:    * @see ThreadGroup#uncaughtException(Thread, Throwable)
 942:    * @see SecurityManager#checkAccess(Thread)
 943:    * @see SecurityManager#checkPermission(Permission)
 944:    * @deprecated unsafe operation, try not to use
 945:    */
 946:   public final void stop()
 947:   {
 948:     stop(new ThreadDeath());
 949:   }
 950: 
 951:   /**
 952:    * Cause this Thread to stop abnormally and throw the specified exception.
 953:    * If you stop a Thread that has not yet started, the stop is ignored
 954:    * (contrary to what the JDK documentation says).
 955:    * <b>WARNING</b>This bypasses Java security, and can throw a checked
 956:    * exception which the call stack is unprepared to handle. Do not abuse
 957:    * this power.
 958:    *
 959:    * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
 960:    * leave data in bad states.  Hence, there is a security check:
 961:    * <code>checkAccess(this)</code>, plus another one if the current thread
 962:    * is not this: <code>RuntimePermission("stopThread")</code>. If you must
 963:    * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
 964:    * ThreadDeath is the only exception which does not print a stack trace when
 965:    * the thread dies.
 966:    *
 967:    * @param t the Throwable to throw when the Thread dies
 968:    * @throws SecurityException if you cannot stop the Thread
 969:    * @throws NullPointerException in the calling thread, if t is null
 970:    * @see #interrupt()
 971:    * @see #checkAccess()
 972:    * @see #start()
 973:    * @see ThreadDeath
 974:    * @see ThreadGroup#uncaughtException(Thread, Throwable)
 975:    * @see SecurityManager#checkAccess(Thread)
 976:    * @see SecurityManager#checkPermission(Permission)
 977:    * @deprecated unsafe operation, try not to use
 978:    */
 979:   public final synchronized void stop(Throwable t)
 980:   {
 981:     if (t == null)
 982:       throw new NullPointerException();
 983:     // Bypass System.getSecurityManager, for bootstrap efficiency.
 984:     SecurityManager sm = SecurityManager.current;
 985:     if (sm != null)
 986:       {
 987:         sm.checkAccess(this);
 988:         if (this != currentThread() || !(t instanceof ThreadDeath))
 989:           sm.checkPermission(new RuntimePermission("stopThread"));
 990:       }
 991:     VMThread vt = vmThread;
 992:     if (vt != null)
 993:     vt.stop(t);
 994:     else
 995:     stillborn = t;
 996:   }
 997: 
 998:   /**
 999:    * Suspend this Thread.  It will not come back, ever, unless it is resumed.
1000:    *
1001:    * <p>This is inherently unsafe, as the suspended thread still holds locks,
1002:    * and can potentially deadlock your program.  Hence, there is a security
1003:    * check: <code>checkAccess</code>.
1004:    *
1005:    * @throws SecurityException if you cannot suspend the Thread
1006:    * @see #checkAccess()
1007:    * @see #resume()
1008:    * @deprecated unsafe operation, try not to use
1009:    */
1010:   public final synchronized void suspend()
1011:   {
1012:     checkAccess();
1013:     VMThread t = vmThread;
1014:     if (t != null)
1015:       t.suspend();
1016:   }
1017: 
1018:   /**
1019:    * Set this Thread's priority. There may be a security check,
1020:    * <code>checkAccess</code>, then the priority is set to the smaller of
1021:    * priority and the ThreadGroup maximum priority.
1022:    *
1023:    * @param priority the new priority for this Thread
1024:    * @throws IllegalArgumentException if priority exceeds MIN_PRIORITY or
1025:    *         MAX_PRIORITY
1026:    * @throws SecurityException if you cannot modify this Thread
1027:    * @see #getPriority()
1028:    * @see #checkAccess()
1029:    * @see ThreadGroup#getMaxPriority()
1030:    * @see #MIN_PRIORITY
1031:    * @see #MAX_PRIORITY
1032:    */
1033:   public final synchronized void setPriority(int priority)
1034:   {
1035:     checkAccess();
1036:     if (priority < MIN_PRIORITY || priority > MAX_PRIORITY)
1037:       throw new IllegalArgumentException("Invalid thread priority value "
1038:                                          + priority + ".");
1039:     priority = Math.min(priority, group.getMaxPriority());
1040:     VMThread t = vmThread;
1041:     if (t != null)
1042:       t.setPriority(priority);
1043:     else
1044:       this.priority = priority;
1045:   }
1046: 
1047:   /**
1048:    * Returns a string representation of this thread, including the
1049:    * thread's name, priority, and thread group.
1050:    *
1051:    * @return a human-readable String representing this Thread
1052:    */
1053:   public String toString()
1054:   {
1055:     return ("Thread[" + name + "," + priority + ","
1056:         + (group == null ? "" : group.getName()) + "]");
1057:   }
1058: 
1059:   /**
1060:    * Clean up code, called by VMThread when thread dies.
1061:    */
1062:   synchronized void die()
1063:   {
1064:     group.removeThread(this);
1065:     vmThread = null;
1066:     locals = null;
1067:   }
1068: 
1069:   /**
1070:    * Returns the map used by ThreadLocal to store the thread local values.
1071:    */
1072:   static Map getThreadLocals()
1073:   {
1074:     Thread thread = currentThread();
1075:     Map locals = thread.locals;
1076:     if (locals == null)
1077:       {
1078:         locals = thread.locals = new WeakIdentityHashMap();
1079:       }
1080:     return locals;
1081:   }
1082: 
1083:   /** 
1084:    * Assigns the given <code>UncaughtExceptionHandler</code> to this
1085:    * thread.  This will then be called if the thread terminates due
1086:    * to an uncaught exception, pre-empting that of the
1087:    * <code>ThreadGroup</code>.
1088:    *
1089:    * @param h the handler to use for this thread.
1090:    * @throws SecurityException if the current thread can't modify this thread.
1091:    * @since 1.5 
1092:    */
1093:   public void setUncaughtExceptionHandler(UncaughtExceptionHandler h)
1094:   {
1095:     SecurityManager sm = SecurityManager.current; // Be thread-safe.
1096:     if (sm != null)
1097:       sm.checkAccess(this);    
1098:     exceptionHandler = h;
1099:   }
1100: 
1101:   /** 
1102:    * <p>
1103:    * Returns the handler used when this thread terminates due to an
1104:    * uncaught exception.  The handler used is determined by the following:
1105:    * </p>
1106:    * <ul>
1107:    * <li>If this thread has its own handler, this is returned.</li>
1108:    * <li>If not, then the handler of the thread's <code>ThreadGroup</code>
1109:    * object is returned.</li>
1110:    * <li>If both are unavailable, then <code>null</code> is returned
1111:    *     (which can only happen when the thread was terminated since
1112:    *      then it won't have an associated thread group anymore).</li>
1113:    * </ul>
1114:    * 
1115:    * @return the appropriate <code>UncaughtExceptionHandler</code> or
1116:    *         <code>null</code> if one can't be obtained.
1117:    * @since 1.5 
1118:    */
1119:   public UncaughtExceptionHandler getUncaughtExceptionHandler()
1120:   {
1121:     return exceptionHandler != null ? exceptionHandler : group;
1122:   }
1123: 
1124:   /** 
1125:    * <p>
1126:    * Sets the default uncaught exception handler used when one isn't
1127:    * provided by the thread or its associated <code>ThreadGroup</code>.
1128:    * This exception handler is used when the thread itself does not
1129:    * have an exception handler, and the thread's <code>ThreadGroup</code>
1130:    * does not override this default mechanism with its own.  As the group
1131:    * calls this handler by default, this exception handler should not defer
1132:    * to that of the group, as it may lead to infinite recursion.
1133:    * </p>
1134:    * <p>
1135:    * Uncaught exception handlers are used when a thread terminates due to
1136:    * an uncaught exception.  Replacing this handler allows default code to
1137:    * be put in place for all threads in order to handle this eventuality.
1138:    * </p>
1139:    *
1140:    * @param h the new default uncaught exception handler to use.
1141:    * @throws SecurityException if a security manager is present and
1142:    *                           disallows the runtime permission
1143:    *                           "setDefaultUncaughtExceptionHandler".
1144:    * @since 1.5 
1145:    */
1146:   public static void 
1147:     setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler h)
1148:   {
1149:     SecurityManager sm = SecurityManager.current; // Be thread-safe.
1150:     if (sm != null)
1151:       sm.checkPermission(new RuntimePermission("setDefaultUncaughtExceptionHandler"));    
1152:     defaultHandler = h;
1153:   }
1154: 
1155:   /** 
1156:    * Returns the handler used by default when a thread terminates
1157:    * unexpectedly due to an exception, or <code>null</code> if one doesn't
1158:    * exist.
1159:    *
1160:    * @return the default uncaught exception handler.
1161:    * @since 1.5 
1162:    */
1163:   public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
1164:   {
1165:     return defaultHandler;
1166:   }
1167:   
1168:   /** 
1169:    * Returns the unique identifier for this thread.  This ID is generated
1170:    * on thread creation, and may be re-used on its death.
1171:    *
1172:    * @return a positive long number representing the thread's ID.
1173:    * @since 1.5 
1174:    */
1175:   public long getId()
1176:   {
1177:     return threadId;
1178:   }
1179: 
1180:   /**
1181:    * <p>
1182:    * This interface is used to handle uncaught exceptions
1183:    * which cause a <code>Thread</code> to terminate.  When
1184:    * a thread, t, is about to terminate due to an uncaught
1185:    * exception, the virtual machine looks for a class which
1186:    * implements this interface, in order to supply it with
1187:    * the dying thread and its uncaught exception.
1188:    * </p>
1189:    * <p>
1190:    * The virtual machine makes two attempts to find an
1191:    * appropriate handler for the uncaught exception, in
1192:    * the following order:
1193:    * </p>
1194:    * <ol>
1195:    * <li>
1196:    * <code>t.getUncaughtExceptionHandler()</code> --
1197:    * the dying thread is queried first for a handler
1198:    * specific to that thread.
1199:    * </li>
1200:    * <li>
1201:    * <code>t.getThreadGroup()</code> --
1202:    * the thread group of the dying thread is used to
1203:    * handle the exception.  If the thread group has
1204:    * no special requirements for handling the exception,
1205:    * it may simply forward it on to
1206:    * <code>Thread.getDefaultUncaughtExceptionHandler()</code>,
1207:    * the default handler, which is used as a last resort.
1208:    * </li>
1209:    * </ol>
1210:    * <p>
1211:    * The first handler found is the one used to handle
1212:    * the uncaught exception.
1213:    * </p>
1214:    *
1215:    * @author Tom Tromey <tromey@redhat.com>
1216:    * @author Andrew John Hughes <gnu_andrew@member.fsf.org>
1217:    * @since 1.5
1218:    * @see Thread#getUncaughtExceptionHandler()
1219:    * @see Thread#setUncaughtExceptionHandler(UncaughtExceptionHandler)
1220:    * @see Thread#getDefaultUncaughtExceptionHandler()
1221:    * @see
1222:    * Thread#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)
1223:    */
1224:   public interface UncaughtExceptionHandler
1225:   {
1226:     /**
1227:      * Invoked by the virtual machine with the dying thread
1228:      * and the uncaught exception.  Any exceptions thrown
1229:      * by this method are simply ignored by the virtual
1230:      * machine.
1231:      *
1232:      * @param thr the dying thread.
1233:      * @param exc the uncaught exception.
1234:      */
1235:     void uncaughtException(Thread thr, Throwable exc);
1236:   }
1237: 
1238:   /** 
1239:    * <p>
1240:    * Represents the current state of a thread, according to the VM rather
1241:    * than the operating system.  It can be one of the following:
1242:    * </p>
1243:    * <ul>
1244:    * <li>NEW -- The thread has just been created but is not yet running.</li>
1245:    * <li>RUNNABLE -- The thread is currently running or can be scheduled
1246:    * to run.</li>
1247:    * <li>BLOCKED -- The thread is blocked waiting on an I/O operation
1248:    * or to obtain a lock.</li>
1249:    * <li>WAITING -- The thread is waiting indefinitely for another thread
1250:    * to do something.</li>
1251:    * <li>TIMED_WAITING -- The thread is waiting for a specific amount of time
1252:    * for another thread to do something.</li>
1253:    * <li>TERMINATED -- The thread has exited.</li>
1254:    * </ul>
1255:    *
1256:    * @since 1.5 
1257:    */
1258:   public enum State
1259:   {
1260:     BLOCKED, NEW, RUNNABLE, TERMINATED, TIMED_WAITING, WAITING;
1261: 
1262:     /**
1263:      * For compatability with Sun's JDK
1264:      */
1265:     private static final long serialVersionUID = 605505746047245783L;
1266:   }
1267: 
1268: 
1269:   /**
1270:    * Returns the current state of the thread.  This
1271:    * is designed for monitoring thread behaviour, rather
1272:    * than for synchronization control.
1273:    *
1274:    * @return the current thread state.
1275:    */
1276:   public State getState()
1277:   {
1278:     VMThread t = vmThread;
1279:     if (t != null)
1280:       return State.valueOf(t.getState());
1281:     if (group == null)
1282:       return State.TERMINATED;
1283:     return State.NEW;
1284:   }
1285: 
1286:   /**
1287:    * <p>
1288:    * Returns a map of threads to stack traces for each
1289:    * live thread.  The keys of the map are {@link Thread}
1290:    * objects, which map to arrays of {@link StackTraceElement}s.
1291:    * The results obtained from Calling this method are
1292:    * equivalent to calling {@link getStackTrace()} on each
1293:    * thread in succession.  Threads may be executing while
1294:    * this takes place, and the results represent a snapshot
1295:    * of the thread at the time its {@link getStackTrace()}
1296:    * method is called.
1297:    * </p>
1298:    * <p>
1299:    * The stack trace information contains the methods called
1300:    * by the thread, with the most recent method forming the
1301:    * first element in the array.  The array will be empty
1302:    * if the virtual machine can not obtain information on the
1303:    * thread. 
1304:    * </p>
1305:    * <p>
1306:    * To execute this method, the current security manager
1307:    * (if one exists) must allow both the
1308:    * <code>"getStackTrace"</code> and
1309:    * <code>"modifyThreadGroup"</code> {@link RuntimePermission}s.
1310:    * </p>
1311:    * 
1312:    * @return a map of threads to arrays of {@link StackTraceElement}s.
1313:    * @throws SecurityException if a security manager exists, and
1314:    *                           prevents either or both the runtime
1315:    *                           permissions specified above.
1316:    * @since 1.5
1317:    * @see #getStackTrace()
1318:    */
1319:   public static Map<Thread, StackTraceElement[]> getAllStackTraces()
1320:   {
1321:     ThreadGroup group = currentThread().group;
1322:     while (group.getParent() != null)
1323:       group = group.getParent();
1324:     int arraySize = group.activeCount();
1325:     Thread[] threadList = new Thread[arraySize];
1326:     int filled = group.enumerate(threadList);
1327:     while (filled == arraySize)
1328:       {
1329:     arraySize *= 2;
1330:     threadList = new Thread[arraySize];
1331:     filled = group.enumerate(threadList);
1332:       }
1333:     Map traces = new HashMap();
1334:     for (int a = 0; a < filled; ++a)
1335:       traces.put(threadList[a],
1336:          threadList[a].getStackTrace());
1337:     return traces;
1338:   }
1339: 
1340:   /**
1341:    * <p>
1342:    * Returns an array of {@link StackTraceElement}s
1343:    * representing the current stack trace of this thread.
1344:    * The first element of the array is the most recent
1345:    * method called, and represents the top of the stack.
1346:    * The elements continue in this order, with the last
1347:    * element representing the bottom of the stack.
1348:    * </p>
1349:    * <p>
1350:    * A zero element array is returned for threads which
1351:    * have not yet started (and thus have not yet executed
1352:    * any methods) or for those which have terminated.
1353:    * Where the virtual machine can not obtain a trace for
1354:    * the thread, an empty array is also returned.  The
1355:    * virtual machine may also omit some methods from the
1356:    * trace in non-zero arrays.
1357:    * </p>
1358:    * <p>
1359:    * To execute this method, the current security manager
1360:    * (if one exists) must allow both the
1361:    * <code>"getStackTrace"</code> and
1362:    * <code>"modifyThreadGroup"</code> {@link RuntimePermission}s.
1363:    * </p>
1364:    *
1365:    * @return a stack trace for this thread.
1366:    * @throws SecurityException if a security manager exists, and
1367:    *                           prevents the use of the
1368:    *                           <code>"getStackTrace"</code>
1369:    *                           permission.
1370:    * @since 1.5
1371:    * @see #getAllStackTraces()
1372:    */
1373:   public StackTraceElement[] getStackTrace()
1374:   {
1375:     SecurityManager sm = SecurityManager.current; // Be thread-safe.
1376:     if (sm != null)
1377:       sm.checkPermission(new RuntimePermission("getStackTrace"));
1378:     ThreadMXBean bean = ManagementFactory.getThreadMXBean();
1379:     ThreadInfo info = bean.getThreadInfo(threadId, Integer.MAX_VALUE);
1380:     return info.getStackTrace();
1381:   }
1382: 
1383: }