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