Thread.java 47 KB

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