Thread.java 47 KB

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