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: 
  40: package java.lang;
  41: 
  42: import gnu.gcj.RawData;
  43: import gnu.gcj.RawDataManaged;
  44: import gnu.java.util.WeakIdentityHashMap;
  45: import java.util.Map;
  46: 
  47: /* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3
  48:  * "The Java Language Specification", ISBN 0-201-63451-1
  49:  * plus online API docs for JDK 1.2 beta from http://www.javasoft.com.
  50:  * Status:  Believed complete to version 1.4, with caveats. We do not
  51:  *          implement the deprecated (and dangerous) stop, suspend, and resume
  52:  *          methods. Security implementation is not complete.
  53:  */
  54: 
  55: /**
  56:  * Thread represents a single thread of execution in the VM. When an
  57:  * application VM starts up, it creates a non-daemon Thread which calls the
  58:  * main() method of a particular class.  There may be other Threads running,
  59:  * such as the garbage collection thread.
  60:  *
  61:  * <p>Threads have names to identify them.  These names are not necessarily
  62:  * unique. Every Thread has a priority, as well, which tells the VM which
  63:  * Threads should get more running time. New threads inherit the priority
  64:  * and daemon status of the parent thread, by default.
  65:  *
  66:  * <p>There are two methods of creating a Thread: you may subclass Thread and
  67:  * implement the <code>run()</code> method, at which point you may start the
  68:  * Thread by calling its <code>start()</code> method, or you may implement
  69:  * <code>Runnable</code> in the class you want to use and then call new
  70:  * <code>Thread(your_obj).start()</code>.
  71:  *
  72:  * <p>The virtual machine runs until all non-daemon threads have died (either
  73:  * by returning from the run() method as invoked by start(), or by throwing
  74:  * an uncaught exception); or until <code>System.exit</code> is called with
  75:  * adequate permissions.
  76:  *
  77:  * <p>It is unclear at what point a Thread should be added to a ThreadGroup,
  78:  * and at what point it should be removed. Should it be inserted when it
  79:  * starts, or when it is created?  Should it be removed when it is suspended
  80:  * or interrupted?  The only thing that is clear is that the Thread should be
  81:  * removed when it is stopped.
  82:  *
  83:  * @author Tom Tromey
  84:  * @author John Keiser
  85:  * @author Eric Blake (ebb9@email.byu.edu)
  86:  * @see Runnable
  87:  * @see Runtime#exit(int)
  88:  * @see #run()
  89:  * @see #start()
  90:  * @see ThreadLocal
  91:  * @since 1.0
  92:  * @status updated to 1.4
  93:  */
  94: public class Thread implements Runnable
  95: {
  96:   /** The minimum priority for a Thread. */
  97:   public static final int MIN_PRIORITY = 1;
  98: 
  99:   /** The priority a Thread gets by default. */
 100:   public static final int NORM_PRIORITY = 5;
 101: 
 102:   /** The maximum priority for a Thread. */
 103:   public static final int MAX_PRIORITY = 10;
 104: 
 105:   /**
 106:    * The group this thread belongs to. This is set to null by
 107:    * ThreadGroup.removeThread when the thread dies.
 108:    */
 109:   ThreadGroup group;
 110: 
 111:   /** The object to run(), null if this is the target. */
 112:   private Runnable runnable;
 113: 
 114:   /** The thread name, non-null. */
 115:   String name;
 116: 
 117:   /** Whether the thread is a daemon. */
 118:   private boolean daemon;
 119: 
 120:   /** The thread priority, 1 to 10. */
 121:   private int priority;
 122: 
 123:   boolean interrupt_flag;
 124:   private boolean alive_flag;
 125:   private boolean startable_flag;
 126: 
 127:   /** The context classloader for this Thread. */
 128:   private ClassLoader contextClassLoader;
 129: 
 130:   /** This thread's ID.  */
 131:   private final long threadId;
 132: 
 133:   /** The next thread ID to use.  */
 134:   private static long nextThreadId;
 135: 
 136:   /** The default exception handler.  */
 137:   private static UncaughtExceptionHandler defaultHandler;
 138: 
 139:   /** Thread local storage. Package accessible for use by
 140:     * InheritableThreadLocal.
 141:     */
 142:   WeakIdentityHashMap locals;
 143: 
 144:   /** The uncaught exception handler.  */
 145:   UncaughtExceptionHandler exceptionHandler;
 146: 
 147:   /** The access control state for this thread.  Package accessible
 148:     * for use by java.security.VMAccessControlState's native method.
 149:     */
 150:   Object accessControlState = null;
 151:   
 152:   // This describes the top-most interpreter frame for this thread.
 153:   RawData interp_frame;
 154: 
 155:   // Our native data - points to an instance of struct natThread.
 156:   private RawDataManaged data;
 157: 
 158:   /**
 159:    * Allocates a new <code>Thread</code> object. This constructor has
 160:    * the same effect as <code>Thread(null, null,</code>
 161:    * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
 162:    * a newly generated name. Automatically generated names are of the
 163:    * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
 164:    * <p>
 165:    * Threads created this way must have overridden their
 166:    * <code>run()</code> method to actually do anything.  An example
 167:    * illustrating this method being used follows:
 168:    * <p><blockquote><pre>
 169:    *     import java.lang.*;
 170:    *
 171:    *     class plain01 implements Runnable {
 172:    *         String name;
 173:    *         plain01() {
 174:    *             name = null;
 175:    *         }
 176:    *         plain01(String s) {
 177:    *             name = s;
 178:    *         }
 179:    *         public void run() {
 180:    *             if (name == null)
 181:    *                 System.out.println("A new thread created");
 182:    *             else
 183:    *                 System.out.println("A new thread with name " + name +
 184:    *                                    " created");
 185:    *         }
 186:    *     }
 187:    *     class threadtest01 {
 188:    *         public static void main(String args[] ) {
 189:    *             int failed = 0 ;
 190:    *
 191:    *             <b>Thread t1 = new Thread();</b>
 192:    *             if (t1 != null)
 193:    *                 System.out.println("new Thread() succeed");
 194:    *             else {
 195:    *                 System.out.println("new Thread() failed");
 196:    *                 failed++;
 197:    *             }
 198:    *         }
 199:    *     }
 200:    * </pre></blockquote>
 201:    *
 202:    * @see     java.lang.Thread#Thread(java.lang.ThreadGroup,
 203:    *          java.lang.Runnable, java.lang.String)
 204:    */
 205:   public Thread()
 206:   {
 207:     this(null, null, gen_name());
 208:   }
 209: 
 210:   /**
 211:    * Allocates a new <code>Thread</code> object. This constructor has
 212:    * the same effect as <code>Thread(null, target,</code>
 213:    * <i>gname</i><code>)</code>, where <i>gname</i> is
 214:    * a newly generated name. Automatically generated names are of the
 215:    * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
 216:    *
 217:    * @param target the object whose <code>run</code> method is called.
 218:    * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
 219:    *                              java.lang.Runnable, java.lang.String)
 220:    */
 221:   public Thread(Runnable target)
 222:   {
 223:     this(null, target, gen_name());
 224:   }
 225: 
 226:   /**
 227:    * Allocates a new <code>Thread</code> object. This constructor has
 228:    * the same effect as <code>Thread(null, null, name)</code>.
 229:    *
 230:    * @param   name   the name of the new thread.
 231:    * @see     java.lang.Thread#Thread(java.lang.ThreadGroup,
 232:    *          java.lang.Runnable, java.lang.String)
 233:    */
 234:   public Thread(String name)
 235:   {
 236:     this(null, null, name);
 237:   }
 238: 
 239:   /**
 240:    * Allocates a new <code>Thread</code> object. This constructor has
 241:    * the same effect as <code>Thread(group, target,</code>
 242:    * <i>gname</i><code>)</code>, where <i>gname</i> is
 243:    * a newly generated name. Automatically generated names are of the
 244:    * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
 245:    *
 246:    * @param group the group to put the Thread into
 247:    * @param target the Runnable object to execute
 248:    * @throws SecurityException if this thread cannot access <code>group</code>
 249:    * @throws IllegalThreadStateException if group is destroyed
 250:    * @see #Thread(ThreadGroup, Runnable, String)
 251:    */
 252:   public Thread(ThreadGroup group, Runnable target)
 253:   {
 254:     this(group, target, gen_name());
 255:   }
 256: 
 257:   /**
 258:    * Allocates a new <code>Thread</code> object. This constructor has
 259:    * the same effect as <code>Thread(group, null, name)</code>
 260:    *
 261:    * @param group the group to put the Thread into
 262:    * @param name the name for the Thread
 263:    * @throws NullPointerException if name is null
 264:    * @throws SecurityException if this thread cannot access <code>group</code>
 265:    * @throws IllegalThreadStateException if group is destroyed
 266:    * @see #Thread(ThreadGroup, Runnable, String)
 267:    */
 268:   public Thread(ThreadGroup group, String name)
 269:   {
 270:     this(group, null, name);
 271:   }
 272: 
 273:   /**
 274:    * Allocates a new <code>Thread</code> object. This constructor has
 275:    * the same effect as <code>Thread(null, target, name)</code>.
 276:    *
 277:    * @param target the Runnable object to execute
 278:    * @param name the name for the Thread
 279:    * @throws NullPointerException if name is null
 280:    * @see #Thread(ThreadGroup, Runnable, String)
 281:    */
 282:   public Thread(Runnable target, String name)
 283:   {
 284:     this(null, target, name);
 285:   }
 286: 
 287:   /**
 288:    * Allocate a new Thread object, with the specified ThreadGroup and name, and
 289:    * using the specified Runnable object's <code>run()</code> method to
 290:    * execute.  If the Runnable object is null, <code>this</code> (which is
 291:    * a Runnable) is used instead.
 292:    *
 293:    * <p>If the ThreadGroup is null, the security manager is checked. If a
 294:    * manager exists and returns a non-null object for
 295:    * <code>getThreadGroup</code>, that group is used; otherwise the group
 296:    * of the creating thread is used. Note that the security manager calls
 297:    * <code>checkAccess</code> if the ThreadGroup is not null.
 298:    *
 299:    * <p>The new Thread will inherit its creator's priority and daemon status.
 300:    * These can be changed with <code>setPriority</code> and
 301:    * <code>setDaemon</code>.
 302:    *
 303:    * @param group the group to put the Thread into
 304:    * @param target the Runnable object to execute
 305:    * @param name the name for the Thread
 306:    * @throws NullPointerException if name is null
 307:    * @throws SecurityException if this thread cannot access <code>group</code>
 308:    * @throws IllegalThreadStateException if group is destroyed
 309:    * @see Runnable#run()
 310:    * @see #run()
 311:    * @see #setDaemon(boolean)
 312:    * @see #setPriority(int)
 313:    * @see SecurityManager#checkAccess(ThreadGroup)
 314:    * @see ThreadGroup#checkAccess()
 315:    */
 316:   public Thread(ThreadGroup group, Runnable target, String name)
 317:   {
 318:     this(currentThread(), group, target, name);
 319:   }
 320: 
 321:   /**
 322:    * Allocate a new Thread object, as if by
 323:    * <code>Thread(group, null, name)</code>, and give it the specified stack
 324:    * size, in bytes. The stack size is <b>highly platform independent</b>,
 325:    * and the virtual machine is free to round up or down, or ignore it
 326:    * completely.  A higher value might let you go longer before a
 327:    * <code>StackOverflowError</code>, while a lower value might let you go
 328:    * longer before an <code>OutOfMemoryError</code>.  Or, it may do absolutely
 329:    * nothing! So be careful, and expect to need to tune this value if your
 330:    * virtual machine even supports it.
 331:    *
 332:    * @param group the group to put the Thread into
 333:    * @param target the Runnable object to execute
 334:    * @param name the name for the Thread
 335:    * @param size the stack size, in bytes; 0 to be ignored
 336:    * @throws NullPointerException if name is null
 337:    * @throws SecurityException if this thread cannot access <code>group</code>
 338:    * @throws IllegalThreadStateException if group is destroyed
 339:    * @since 1.4
 340:    */
 341:   public Thread(ThreadGroup group, Runnable target, String name, long size)
 342:   {
 343:     // Just ignore stackSize for now.
 344:     this(currentThread(), group, target, name);
 345:   }
 346: 
 347:   private Thread (Thread current, ThreadGroup g, Runnable r, String n)
 348:   {
 349:     // Make sure the current thread may create a new thread.
 350:     checkAccess();
 351:     
 352:     // The Class Libraries book says ``threadName cannot be null''.  I
 353:     // take this to mean NullPointerException.
 354:     if (n == null)
 355:       throw new NullPointerException ();
 356:       
 357:     if (g == null)
 358:       {
 359:     // If CURRENT is null, then we are bootstrapping the first thread. 
 360:     // Use ThreadGroup.root, the main threadgroup.
 361:     if (current == null)
 362:       group = ThreadGroup.root;
 363:     else
 364:       group = current.getThreadGroup();
 365:       }
 366:     else
 367:       group = g;
 368: 
 369:     data = null;
 370:     interrupt_flag = false;
 371:     alive_flag = false;
 372:     startable_flag = true;
 373: 
 374:     synchronized (Thread.class)
 375:       {
 376:         this.threadId = nextThreadId++;
 377:       }
 378: 
 379:     if (current != null)
 380:       {
 381:     group.checkAccess();
 382: 
 383:     daemon = current.isDaemon();
 384:         int gmax = group.getMaxPriority();
 385:     int pri = current.getPriority();
 386:     priority = (gmax < pri ? gmax : pri);
 387:     contextClassLoader = current.contextClassLoader;
 388:     InheritableThreadLocal.newChildThread(this);
 389:       }
 390:     else
 391:       {
 392:     daemon = false;
 393:     priority = NORM_PRIORITY;
 394:       }
 395: 
 396:     name = n;
 397:     group.addThread(this);
 398:     runnable = r;
 399: 
 400:     initialize_native ();
 401:   }
 402: 
 403:   /**
 404:    * Get the number of active threads in the current Thread's ThreadGroup.
 405:    * This implementation calls
 406:    * <code>currentThread().getThreadGroup().activeCount()</code>.
 407:    *
 408:    * @return the number of active threads in the current ThreadGroup
 409:    * @see ThreadGroup#activeCount()
 410:    */
 411:   public static int activeCount()
 412:   {
 413:     return currentThread().group.activeCount();
 414:   }
 415: 
 416:   /**
 417:    * Check whether the current Thread is allowed to modify this Thread. This
 418:    * passes the check on to <code>SecurityManager.checkAccess(this)</code>.
 419:    *
 420:    * @throws SecurityException if the current Thread cannot modify this Thread
 421:    * @see SecurityManager#checkAccess(Thread)
 422:    */
 423:   public final void checkAccess()
 424:   {
 425:     SecurityManager sm = System.getSecurityManager();
 426:     if (sm != null)
 427:       sm.checkAccess(this);
 428:   }
 429: 
 430:   /**
 431:    * Count the number of stack frames in this Thread.  The Thread in question
 432:    * must be suspended when this occurs.
 433:    *
 434:    * @return the number of stack frames in this Thread
 435:    * @throws IllegalThreadStateException if this Thread is not suspended
 436:    * @deprecated pointless, since suspend is deprecated
 437:    */
 438:   public native int countStackFrames();
 439: 
 440:   /**
 441:    * Get the currently executing Thread.
 442:    *
 443:    * @return the currently executing Thread
 444:    */
 445:   public static native Thread currentThread();
 446: 
 447:   /**
 448:    * Originally intended to destroy this thread, this method was never
 449:    * implemented by Sun, and is hence a no-op.
 450:    */
 451:   public void destroy()
 452:   {
 453:     throw new NoSuchMethodError();
 454:   }
 455:   
 456:   /**
 457:    * Print a stack trace of the current thread to stderr using the same
 458:    * format as Throwable's printStackTrace() method.
 459:    *
 460:    * @see Throwable#printStackTrace()
 461:    */
 462:   public static void dumpStack()
 463:   {
 464:     (new Exception("Stack trace")).printStackTrace();
 465:   }
 466: 
 467:   /**
 468:    * Copy every active thread in the current Thread's ThreadGroup into the
 469:    * array. Extra threads are silently ignored. This implementation calls
 470:    * <code>getThreadGroup().enumerate(array)</code>, which may have a
 471:    * security check, <code>checkAccess(group)</code>.
 472:    *
 473:    * @param array the array to place the Threads into
 474:    * @return the number of Threads placed into the array
 475:    * @throws NullPointerException if array is null
 476:    * @throws SecurityException if you cannot access the ThreadGroup
 477:    * @see ThreadGroup#enumerate(Thread[])
 478:    * @see #activeCount()
 479:    * @see SecurityManager#checkAccess(ThreadGroup)
 480:    */
 481:   public static int enumerate(Thread[] array)
 482:   {
 483:     return currentThread().group.enumerate(array);
 484:   }
 485:   
 486:   /**
 487:    * Get this Thread's name.
 488:    *
 489:    * @return this Thread's name
 490:    */
 491:   public final String getName()
 492:   {
 493:     return name;
 494:   }
 495: 
 496:   /**
 497:    * Get this Thread's priority.
 498:    *
 499:    * @return the Thread's priority
 500:    */
 501:   public final int getPriority()
 502:   {
 503:     return priority;
 504:   }
 505: 
 506:   /**
 507:    * Get the ThreadGroup this Thread belongs to. If the thread has died, this
 508:    * returns null.
 509:    *
 510:    * @return this Thread's ThreadGroup
 511:    */
 512:   public final ThreadGroup getThreadGroup()
 513:   {
 514:     return group;
 515:   }
 516: 
 517:   /**
 518:    * Checks whether the current thread holds the monitor on a given object.
 519:    * This allows you to do <code>assert Thread.holdsLock(obj)</code>.
 520:    *
 521:    * @param obj the object to test lock ownership on.
 522:    * @return true if the current thread is currently synchronized on obj
 523:    * @throws NullPointerException if obj is null
 524:    * @since 1.4
 525:    */
 526:   public static native boolean holdsLock(Object obj);
 527: 
 528:   /**
 529:    * Interrupt this Thread. First, there is a security check,
 530:    * <code>checkAccess</code>. Then, depending on the current state of the
 531:    * thread, various actions take place:
 532:    *
 533:    * <p>If the thread is waiting because of {@link #wait()},
 534:    * {@link #sleep(long)}, or {@link #join()}, its <i>interrupt status</i>
 535:    * will be cleared, and an InterruptedException will be thrown. Notice that
 536:    * this case is only possible if an external thread called interrupt().
 537:    *
 538:    * <p>If the thread is blocked in an interruptible I/O operation, in
 539:    * {@link java.nio.channels.InterruptibleChannel}, the <i>interrupt
 540:    * status</i> will be set, and ClosedByInterruptException will be thrown.
 541:    *
 542:    * <p>If the thread is blocked on a {@link java.nio.channels.Selector}, the
 543:    * <i>interrupt status</i> will be set, and the selection will return, with
 544:    * a possible non-zero value, as though by the wakeup() method.
 545:    *
 546:    * <p>Otherwise, the interrupt status will be set.
 547:    *
 548:    * @throws SecurityException if you cannot modify this Thread
 549:    */
 550:   public native void interrupt();
 551: 
 552:   /**
 553:    * Determine whether the current Thread has been interrupted, and clear
 554:    * the <i>interrupted status</i> in the process.
 555:    *
 556:    * @return whether the current Thread has been interrupted
 557:    * @see #isInterrupted()
 558:    */
 559:   public static boolean interrupted()
 560:   {
 561:     return currentThread().isInterrupted(true);
 562:   }
 563: 
 564:   /**
 565:    * Determine whether the given Thread has been interrupted, but leave
 566:    * the <i>interrupted status</i> alone in the process.
 567:    *
 568:    * @return whether the Thread has been interrupted
 569:    * @see #interrupted()
 570:    */
 571:   public boolean isInterrupted()
 572:   {
 573:     return interrupt_flag;
 574:   }
 575: 
 576:   /**
 577:    * Determine whether this Thread is alive. A thread which is alive has
 578:    * started and not yet died.
 579:    *
 580:    * @return whether this Thread is alive
 581:    */
 582:   public final synchronized boolean isAlive()
 583:   {
 584:     return alive_flag;
 585:   }
 586: 
 587:   /**
 588:    * Tell whether this is a daemon Thread or not.
 589:    *
 590:    * @return whether this is a daemon Thread or not
 591:    * @see #setDaemon(boolean)
 592:    */
 593:   public final boolean isDaemon()
 594:   {
 595:     return daemon;
 596:   }
 597: 
 598:   /**
 599:    * Wait forever for the Thread in question to die.
 600:    *
 601:    * @throws InterruptedException if the Thread is interrupted; it's
 602:    *         <i>interrupted status</i> will be cleared
 603:    */
 604:   public final void join() throws InterruptedException
 605:   {
 606:     join(0, 0);
 607:   }
 608: 
 609:   /**
 610:    * Wait the specified amount of time for the Thread in question to die.
 611:    *
 612:    * @param ms the number of milliseconds to wait, or 0 for forever
 613:    * @throws InterruptedException if the Thread is interrupted; it's
 614:    *         <i>interrupted status</i> will be cleared
 615:    */
 616:   public final void join(long ms) throws InterruptedException
 617:   {
 618:     join(ms, 0);
 619:   }
 620: 
 621:   /**
 622:    * Wait the specified amount of time for the Thread in question to die.
 623:    *
 624:    * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
 625:    * not offer that fine a grain of timing resolution. Besides, there is
 626:    * no guarantee that this thread can start up immediately when time expires,
 627:    * because some other thread may be active.  So don't expect real-time
 628:    * performance.
 629:    *
 630:    * @param ms the number of milliseconds to wait, or 0 for forever
 631:    * @param ns the number of extra nanoseconds to sleep (0-999999)
 632:    * @throws InterruptedException if the Thread is interrupted; it's
 633:    *         <i>interrupted status</i> will be cleared
 634:    * @throws IllegalArgumentException if ns is invalid
 635:    * @XXX A ThreadListener would be nice, to make this efficient.
 636:    */
 637:   public final native void join(long ms, int ns)
 638:     throws InterruptedException;
 639: 
 640:   /**
 641:    * Resume a suspended thread.
 642:    *
 643:    * @throws SecurityException if you cannot resume the Thread
 644:    * @see #checkAccess()
 645:    * @see #suspend()
 646:    * @deprecated pointless, since suspend is deprecated
 647:    */
 648:   public final native void resume();
 649: 
 650:   private final native void finish_();
 651: 
 652:   /**
 653:    * Determine whether the given Thread has been interrupted, but leave
 654:    * the <i>interrupted status</i> alone in the process.
 655:    *
 656:    * @return whether the current Thread has been interrupted
 657:    * @see #interrupted()
 658:    */
 659:   private boolean isInterrupted(boolean clear_flag)
 660:   {
 661:     boolean r = interrupt_flag;
 662:     if (clear_flag && r)
 663:       {
 664:     // Only clear the flag if we saw it as set. Otherwise this could 
 665:     // potentially cause us to miss an interrupt in a race condition, 
 666:     // because this method is not synchronized.
 667:     interrupt_flag = false;
 668:       }
 669:     return r;
 670:   }
 671:   
 672:   /**
 673:    * The method of Thread that will be run if there is no Runnable object
 674:    * associated with the Thread. Thread's implementation does nothing at all.
 675:    *
 676:    * @see #start()
 677:    * @see #Thread(ThreadGroup, Runnable, String)
 678:    */
 679:   public void run()
 680:   {
 681:     if (runnable != null)
 682:       runnable.run();
 683:   }
 684: 
 685:   /**
 686:    * Set the daemon status of this Thread.  If this is a daemon Thread, then
 687:    * the VM may exit even if it is still running.  This may only be called
 688:    * before the Thread starts running. There may be a security check,
 689:    * <code>checkAccess</code>.
 690:    *
 691:    * @param daemon whether this should be a daemon thread or not
 692:    * @throws SecurityException if you cannot modify this Thread
 693:    * @throws IllegalThreadStateException if the Thread is active
 694:    * @see #isDaemon()
 695:    * @see #checkAccess()
 696:    */
 697:   public final void setDaemon(boolean daemon)
 698:   {
 699:     if (!startable_flag)
 700:       throw new IllegalThreadStateException();
 701:     checkAccess();
 702:     this.daemon = daemon;
 703:   }
 704: 
 705:   /**
 706:    * Returns the context classloader of this Thread. The context
 707:    * classloader can be used by code that want to load classes depending
 708:    * on the current thread. Normally classes are loaded depending on
 709:    * the classloader of the current class. There may be a security check
 710:    * for <code>RuntimePermission("getClassLoader")</code> if the caller's
 711:    * class loader is not null or an ancestor of this thread's context class
 712:    * loader.
 713:    *
 714:    * @return the context class loader
 715:    * @throws SecurityException when permission is denied
 716:    * @see setContextClassLoader(ClassLoader)
 717:    * @since 1.2
 718:    */
 719:   public synchronized ClassLoader getContextClassLoader()
 720:   {
 721:     if (contextClassLoader == null)
 722:       contextClassLoader = ClassLoader.getSystemClassLoader();
 723: 
 724:     SecurityManager sm = System.getSecurityManager();
 725:     // FIXME: we can't currently find the caller's class loader.
 726:     ClassLoader callers = null;
 727:     if (sm != null && callers != null)
 728:       {
 729:     // See if the caller's class loader is the same as or an
 730:     // ancestor of this thread's class loader.
 731:     while (callers != null && callers != contextClassLoader)
 732:       {
 733:         // FIXME: should use some internal version of getParent
 734:         // that avoids security checks.
 735:         callers = callers.getParent();
 736:       }
 737: 
 738:     if (callers != contextClassLoader)
 739:       sm.checkPermission(new RuntimePermission("getClassLoader"));
 740:       }
 741: 
 742:     return contextClassLoader;
 743:   }
 744: 
 745:   /**
 746:    * Sets the context classloader for this Thread. When not explicitly set,
 747:    * the context classloader for a thread is the same as the context
 748:    * classloader of the thread that created this thread. The first thread has
 749:    * as context classloader the system classloader. There may be a security
 750:    * check for <code>RuntimePermission("setContextClassLoader")</code>.
 751:    *
 752:    * @param classloader the new context class loader
 753:    * @throws SecurityException when permission is denied
 754:    * @see getContextClassLoader()
 755:    * @since 1.2
 756:    */
 757:   public synchronized void setContextClassLoader(ClassLoader classloader)
 758:   {
 759:     SecurityManager sm = System.getSecurityManager();
 760:     if (sm != null)
 761:       sm.checkPermission(new RuntimePermission("setContextClassLoader"));
 762:     this.contextClassLoader = classloader;
 763:   }
 764: 
 765:   /**
 766:    * Set this Thread's name.  There may be a security check,
 767:    * <code>checkAccess</code>.
 768:    *
 769:    * @param name the new name for this Thread
 770:    * @throws NullPointerException if name is null
 771:    * @throws SecurityException if you cannot modify this Thread
 772:    */
 773:   public final void setName(String name)
 774:   {
 775:     checkAccess();
 776:     // The Class Libraries book says ``threadName cannot be null''.  I
 777:     // take this to mean NullPointerException.
 778:     if (name == null)
 779:       throw new NullPointerException();
 780:     this.name = name;
 781:   }
 782: 
 783:   /**
 784:    * Causes the currently executing thread object to temporarily pause
 785:    * and allow other threads to execute.
 786:    */
 787:   public static native void yield();
 788: 
 789:   /**
 790:    * Suspend the current Thread's execution for the specified amount of
 791:    * time. The Thread will not lose any locks it has during this time. There
 792:    * are no guarantees which thread will be next to run, but most VMs will
 793:    * choose the highest priority thread that has been waiting longest.
 794:    *
 795:    * @param ms the number of milliseconds to sleep, or 0 for forever
 796:    * @throws InterruptedException if the Thread is interrupted; it's
 797:    *         <i>interrupted status</i> will be cleared
 798:    * @see #notify()
 799:    * @see #wait(long)
 800:    */
 801:   public static void sleep(long ms) throws InterruptedException
 802:   {
 803:     sleep(ms, 0);
 804:   }
 805: 
 806:   /**
 807:    * Suspend the current Thread's execution for the specified amount of
 808:    * time. The Thread will not lose any locks it has during this time. There
 809:    * are no guarantees which thread will be next to run, but most VMs will
 810:    * choose the highest priority thread that has been waiting longest.
 811:    *
 812:    * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
 813:    * not offer that fine a grain of timing resolution. Besides, there is
 814:    * no guarantee that this thread can start up immediately when time expires,
 815:    * because some other thread may be active.  So don't expect real-time
 816:    * performance.
 817:    *
 818:    * @param ms the number of milliseconds to sleep, or 0 for forever
 819:    * @param ns the number of extra nanoseconds to sleep (0-999999)
 820:    * @throws InterruptedException if the Thread is interrupted; it's
 821:    *         <i>interrupted status</i> will be cleared
 822:    * @throws IllegalArgumentException if ns is invalid
 823:    * @see #notify()
 824:    * @see #wait(long, int)
 825:    */
 826:   public static native void sleep(long timeout, int nanos)
 827:     throws InterruptedException;
 828: 
 829:   /**
 830:    * Start this Thread, calling the run() method of the Runnable this Thread
 831:    * was created with, or else the run() method of the Thread itself. This
 832:    * is the only way to start a new thread; calling run by yourself will just
 833:    * stay in the same thread. The virtual machine will remove the thread from
 834:    * its thread group when the run() method completes.
 835:    *
 836:    * @throws IllegalThreadStateException if the thread has already started
 837:    * @see #run()
 838:    */
 839:   public native void start();
 840: 
 841:   /**
 842:    * Cause this Thread to stop abnormally because of the throw of a ThreadDeath
 843:    * error. If you stop a Thread that has not yet started, it will stop
 844:    * immediately when it is actually started.
 845:    *
 846:    * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
 847:    * leave data in bad states.  Hence, there is a security check:
 848:    * <code>checkAccess(this)</code>, plus another one if the current thread
 849:    * is not this: <code>RuntimePermission("stopThread")</code>. If you must
 850:    * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
 851:    * ThreadDeath is the only exception which does not print a stack trace when
 852:    * the thread dies.
 853:    *
 854:    * @throws SecurityException if you cannot stop the Thread
 855:    * @see #interrupt()
 856:    * @see #checkAccess()
 857:    * @see #start()
 858:    * @see ThreadDeath
 859:    * @see ThreadGroup#uncaughtException(Thread, Throwable)
 860:    * @see SecurityManager#checkAccess(Thread)
 861:    * @see SecurityManager#checkPermission(Permission)
 862:    * @deprecated unsafe operation, try not to use
 863:    */
 864:   public final void stop()
 865:   {
 866:     // Argument doesn't matter, because this is no longer
 867:     // supported.
 868:     stop(null);
 869:   }
 870: 
 871:   /**
 872:    * Cause this Thread to stop abnormally and throw the specified exception.
 873:    * If you stop a Thread that has not yet started, it will stop immediately
 874:    * when it is actually started. <b>WARNING</b>This bypasses Java security,
 875:    * and can throw a checked exception which the call stack is unprepared to
 876:    * handle. Do not abuse this power.
 877:    *
 878:    * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
 879:    * leave data in bad states.  Hence, there is a security check:
 880:    * <code>checkAccess(this)</code>, plus another one if the current thread
 881:    * is not this: <code>RuntimePermission("stopThread")</code>. If you must
 882:    * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
 883:    * ThreadDeath is the only exception which does not print a stack trace when
 884:    * the thread dies.
 885:    *
 886:    * @param t the Throwable to throw when the Thread dies
 887:    * @throws SecurityException if you cannot stop the Thread
 888:    * @throws NullPointerException in the calling thread, if t is null
 889:    * @see #interrupt()
 890:    * @see #checkAccess()
 891:    * @see #start()
 892:    * @see ThreadDeath
 893:    * @see ThreadGroup#uncaughtException(Thread, Throwable)
 894:    * @see SecurityManager#checkAccess(Thread)
 895:    * @see SecurityManager#checkPermission(Permission)
 896:    * @deprecated unsafe operation, try not to use
 897:    */
 898:   public final native void stop(Throwable t);
 899: 
 900:   /**
 901:    * Suspend this Thread.  It will not come back, ever, unless it is resumed.
 902:    *
 903:    * <p>This is inherently unsafe, as the suspended thread still holds locks,
 904:    * and can potentially deadlock your program.  Hence, there is a security
 905:    * check: <code>checkAccess</code>.
 906:    *
 907:    * @throws SecurityException if you cannot suspend the Thread
 908:    * @see #checkAccess()
 909:    * @see #resume()
 910:    * @deprecated unsafe operation, try not to use
 911:    */
 912:   public final native void suspend();
 913: 
 914:   /**
 915:    * Set this Thread's priority. There may be a security check,
 916:    * <code>checkAccess</code>, then the priority is set to the smaller of
 917:    * priority and the ThreadGroup maximum priority.
 918:    *
 919:    * @param priority the new priority for this Thread
 920:    * @throws IllegalArgumentException if priority exceeds MIN_PRIORITY or
 921:    *         MAX_PRIORITY
 922:    * @throws SecurityException if you cannot modify this Thread
 923:    * @see #getPriority()
 924:    * @see #checkAccess()
 925:    * @see ThreadGroup#getMaxPriority()
 926:    * @see #MIN_PRIORITY
 927:    * @see #MAX_PRIORITY
 928:    */
 929:   public final native void setPriority(int newPriority);
 930: 
 931:   /**
 932:    * Returns a string representation of this thread, including the
 933:    * thread's name, priority, and thread group.
 934:    *
 935:    * @return a human-readable String representing this Thread
 936:    */
 937:   public String toString()
 938:   {
 939:     return ("Thread[" + name + "," + priority + ","
 940:         + (group == null ? "" : group.getName()) + "]");
 941:   }
 942: 
 943:   private final native void initialize_native();
 944: 
 945:   private final native static String gen_name();
 946: 
 947:   /**
 948:    * Returns the map used by ThreadLocal to store the thread local values.
 949:    */
 950:   static Map getThreadLocals()
 951:   {
 952:     Thread thread = currentThread();
 953:     Map locals = thread.locals;
 954:     if (locals == null)
 955:       {
 956:         locals = thread.locals = new WeakIdentityHashMap();
 957:       }
 958:     return locals;
 959:   }
 960: 
 961:   /** 
 962:    * Assigns the given <code>UncaughtExceptionHandler</code> to this
 963:    * thread.  This will then be called if the thread terminates due
 964:    * to an uncaught exception, pre-empting that of the
 965:    * <code>ThreadGroup</code>.
 966:    *
 967:    * @param h the handler to use for this thread.
 968:    * @throws SecurityException if the current thread can't modify this thread.
 969:    * @since 1.5 
 970:    */
 971:   public void setUncaughtExceptionHandler(UncaughtExceptionHandler h)
 972:   {
 973:     SecurityManager sm = SecurityManager.current; // Be thread-safe.
 974:     if (sm != null)
 975:       sm.checkAccess(this);    
 976:     exceptionHandler = h;
 977:   }
 978: 
 979:   /** 
 980:    * <p>
 981:    * Returns the handler used when this thread terminates due to an
 982:    * uncaught exception.  The handler used is determined by the following:
 983:    * </p>
 984:    * <ul>
 985:    * <li>If this thread has its own handler, this is returned.</li>
 986:    * <li>If not, then the handler of the thread's <code>ThreadGroup</code>
 987:    * object is returned.</li>
 988:    * <li>If both are unavailable, then <code>null</code> is returned
 989:    *     (which can only happen when the thread was terminated since
 990:    *      then it won't have an associated thread group anymore).</li>
 991:    * </ul>
 992:    * 
 993:    * @return the appropriate <code>UncaughtExceptionHandler</code> or
 994:    *         <code>null</code> if one can't be obtained.
 995:    * @since 1.5 
 996:    */
 997:   public UncaughtExceptionHandler getUncaughtExceptionHandler()
 998:   {
 999:     return exceptionHandler != null ? exceptionHandler : group;
1000:   }
1001: 
1002:   /** 
1003:    * <p>
1004:    * Sets the default uncaught exception handler used when one isn't
1005:    * provided by the thread or its associated <code>ThreadGroup</code>.
1006:    * This exception handler is used when the thread itself does not
1007:    * have an exception handler, and the thread's <code>ThreadGroup</code>
1008:    * does not override this default mechanism with its own.  As the group
1009:    * calls this handler by default, this exception handler should not defer
1010:    * to that of the group, as it may lead to infinite recursion.
1011:    * </p>
1012:    * <p>
1013:    * Uncaught exception handlers are used when a thread terminates due to
1014:    * an uncaught exception.  Replacing this handler allows default code to
1015:    * be put in place for all threads in order to handle this eventuality.
1016:    * </p>
1017:    *
1018:    * @param h the new default uncaught exception handler to use.
1019:    * @throws SecurityException if a security manager is present and
1020:    *                           disallows the runtime permission
1021:    *                           "setDefaultUncaughtExceptionHandler".
1022:    * @since 1.5 
1023:    */
1024:   public static void 
1025:     setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler h)
1026:   {
1027:     SecurityManager sm = SecurityManager.current; // Be thread-safe.
1028:     if (sm != null)
1029:       sm.checkPermission(new RuntimePermission("setDefaultUncaughtExceptionHandler"));    
1030:     defaultHandler = h;
1031:   }
1032: 
1033:   /** 
1034:    * Returns the handler used by default when a thread terminates
1035:    * unexpectedly due to an exception, or <code>null</code> if one doesn't
1036:    * exist.
1037:    *
1038:    * @return the default uncaught exception handler.
1039:    * @since 1.5 
1040:    */
1041:   public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
1042:   {
1043:     return defaultHandler;
1044:   }
1045:   
1046:   /** 
1047:    * Returns the unique identifier for this thread.  This ID is generated
1048:    * on thread creation, and may be re-used on its death.
1049:    *
1050:    * @return a positive long number representing the thread's ID.
1051:    * @since 1.5 
1052:    */
1053:   public long getId()
1054:   {
1055:     return threadId;
1056:   }
1057: 
1058:   /**
1059:    * <p>
1060:    * This interface is used to handle uncaught exceptions
1061:    * which cause a <code>Thread</code> to terminate.  When
1062:    * a thread, t, is about to terminate due to an uncaught
1063:    * exception, the virtual machine looks for a class which
1064:    * implements this interface, in order to supply it with
1065:    * the dying thread and its uncaught exception.
1066:    * </p>
1067:    * <p>
1068:    * The virtual machine makes two attempts to find an
1069:    * appropriate handler for the uncaught exception, in
1070:    * the following order:
1071:    * </p>
1072:    * <ol>
1073:    * <li>
1074:    * <code>t.getUncaughtExceptionHandler()</code> --
1075:    * the dying thread is queried first for a handler
1076:    * specific to that thread.
1077:    * </li>
1078:    * <li>
1079:    * <code>t.getThreadGroup()</code> --
1080:    * the thread group of the dying thread is used to
1081:    * handle the exception.  If the thread group has
1082:    * no special requirements for handling the exception,
1083:    * it may simply forward it on to
1084:    * <code>Thread.getDefaultUncaughtExceptionHandler()</code>,
1085:    * the default handler, which is used as a last resort.
1086:    * </li>
1087:    * </ol>
1088:    * <p>
1089:    * The first handler found is the one used to handle
1090:    * the uncaught exception.
1091:    * </p>
1092:    *
1093:    * @author Tom Tromey <tromey@redhat.com>
1094:    * @author Andrew John Hughes <gnu_andrew@member.fsf.org>
1095:    * @since 1.5
1096:    * @see Thread#getUncaughtExceptionHandler()
1097:    * @see Thread#setUncaughtExceptionHander(java.lang.Thread.UncaughtExceptionHandler)
1098:    * @see Thread#getDefaultUncaughtExceptionHandler()
1099:    * @see
1100:    * Thread#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)
1101:    */
1102:   public interface UncaughtExceptionHandler
1103:   {
1104:     /**
1105:      * Invoked by the virtual machine with the dying thread
1106:      * and the uncaught exception.  Any exceptions thrown
1107:      * by this method are simply ignored by the virtual
1108:      * machine.
1109:      *
1110:      * @param thr the dying thread.
1111:      * @param exc the uncaught exception.
1112:      */
1113:     void uncaughtException(Thread thr, Throwable exc);
1114:   }
1115: 
1116:   /**
1117:    * Returns the current state of the thread.  This
1118:    * is designed for monitoring thread behaviour, rather
1119:    * than for synchronization control.
1120:    *
1121:    * @return the current thread state.
1122:    */
1123:   public String getState()
1124:   {
1125:     // FIXME - Provide real implementation.
1126:     return "NEW";
1127:   }
1128: }