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