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