1. /*
  2. * @(#)Thread.java 1.155 04/06/26
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.lang;
  8. import java.security.AccessController;
  9. import java.security.AccessControlContext;
  10. import java.security.PrivilegedAction;
  11. import java.util.Map;
  12. import java.util.HashMap;
  13. import java.util.Collections;
  14. import java.util.concurrent.locks.LockSupport;
  15. import sun.misc.SoftCache;
  16. import sun.nio.ch.Interruptible;
  17. import sun.security.util.SecurityConstants;
  18. /**
  19. * A <i>thread</i> is a thread of execution in a program. The Java
  20. * Virtual Machine allows an application to have multiple threads of
  21. * execution running concurrently.
  22. * <p>
  23. * Every thread has a priority. Threads with higher priority are
  24. * executed in preference to threads with lower priority. Each thread
  25. * may or may not also be marked as a daemon. When code running in
  26. * some thread creates a new <code>Thread</code> object, the new
  27. * thread has its priority initially set equal to the priority of the
  28. * creating thread, and is a daemon thread if and only if the
  29. * creating thread is a daemon.
  30. * <p>
  31. * When a Java Virtual Machine starts up, there is usually a single
  32. * non-daemon thread (which typically calls the method named
  33. * <code>main</code> of some designated class). The Java Virtual
  34. * Machine continues to execute threads until either of the following
  35. * occurs:
  36. * <ul>
  37. * <li>The <code>exit</code> method of class <code>Runtime</code> has been
  38. * called and the security manager has permitted the exit operation
  39. * to take place.
  40. * <li>All threads that are not daemon threads have died, either by
  41. * returning from the call to the <code>run</code> method or by
  42. * throwing an exception that propagates beyond the <code>run</code>
  43. * method.
  44. * </ul>
  45. * <p>
  46. * There are two ways to create a new thread of execution. One is to
  47. * declare a class to be a subclass of <code>Thread</code>. This
  48. * subclass should override the <code>run</code> method of class
  49. * <code>Thread</code>. An instance of the subclass can then be
  50. * allocated and started. For example, a thread that computes primes
  51. * larger than a stated value could be written as follows:
  52. * <p><hr><blockquote><pre>
  53. * class PrimeThread extends Thread {
  54. * long minPrime;
  55. * PrimeThread(long minPrime) {
  56. * this.minPrime = minPrime;
  57. * }
  58. *
  59. * public void run() {
  60. * // compute primes larger than minPrime
  61. *  . . .
  62. * }
  63. * }
  64. * </pre></blockquote><hr>
  65. * <p>
  66. * The following code would then create a thread and start it running:
  67. * <p><blockquote><pre>
  68. * PrimeThread p = new PrimeThread(143);
  69. * p.start();
  70. * </pre></blockquote>
  71. * <p>
  72. * The other way to create a thread is to declare a class that
  73. * implements the <code>Runnable</code> interface. That class then
  74. * implements the <code>run</code> method. An instance of the class can
  75. * then be allocated, passed as an argument when creating
  76. * <code>Thread</code>, and started. The same example in this other
  77. * style looks like the following:
  78. * <p><hr><blockquote><pre>
  79. * class PrimeRun implements Runnable {
  80. * long minPrime;
  81. * PrimeRun(long minPrime) {
  82. * this.minPrime = minPrime;
  83. * }
  84. *
  85. * public void run() {
  86. * // compute primes larger than minPrime
  87. *  . . .
  88. * }
  89. * }
  90. * </pre></blockquote><hr>
  91. * <p>
  92. * The following code would then create a thread and start it running:
  93. * <p><blockquote><pre>
  94. * PrimeRun p = new PrimeRun(143);
  95. * new Thread(p).start();
  96. * </pre></blockquote>
  97. * <p>
  98. * Every thread has a name for identification purposes. More than
  99. * one thread may have the same name. If a name is not specified when
  100. * a thread is created, a new name is generated for it.
  101. *
  102. * @author unascribed
  103. * @version 1.155, 06/26/04
  104. * @see java.lang.Runnable
  105. * @see java.lang.Runtime#exit(int)
  106. * @see java.lang.Thread#run()
  107. * @see java.lang.Thread#stop()
  108. * @since JDK1.0
  109. */
  110. public
  111. class Thread implements Runnable {
  112. /* Make sure registerNatives is the first thing <clinit> does. */
  113. private static native void registerNatives();
  114. static {
  115. registerNatives();
  116. }
  117. private char name[];
  118. private int priority;
  119. private Thread threadQ;
  120. private long eetop;
  121. private boolean started; // true iff this thread has been started
  122. /* Whether or not to single_step this thread. */
  123. private boolean single_step;
  124. /* Whether or not the thread is a daemon thread. */
  125. private boolean daemon = false;
  126. /* Whether or not this thread was asked to exit before it runs.*/
  127. private boolean stillborn = false;
  128. /* What will be run. */
  129. private Runnable target;
  130. /* The group of this thread */
  131. private ThreadGroup group;
  132. /* The context ClassLoader for this thread */
  133. private ClassLoader contextClassLoader;
  134. /* The inherited AccessControlContext of this thread */
  135. private AccessControlContext inheritedAccessControlContext;
  136. /* For autonumbering anonymous threads. */
  137. private static int threadInitNumber;
  138. private static synchronized int nextThreadNum() {
  139. return threadInitNumber++;
  140. }
  141. /* ThreadLocal values pertaining to this thread. This map is maintained
  142. * by the ThreadLocal class. */
  143. ThreadLocal.ThreadLocalMap threadLocals = null;
  144. /*
  145. * InheritableThreadLocal values pertaining to this thread. This map is
  146. * maintained by the InheritableThreadLocal class.
  147. */
  148. ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
  149. /*
  150. * The requested stack size for this thread, or 0 if the creator did
  151. * not specify a stack size. It is up to the VM to do whatever it
  152. * likes with this number; some VMs will ignore it.
  153. */
  154. private long stackSize;
  155. /*
  156. * Thread ID
  157. */
  158. private long tid;
  159. /* For generating thread ID */
  160. private static long threadSeqNumber;
  161. /* Java thread status for tools,
  162. * initialized to indicate thread 'not yet started'
  163. */
  164. private int threadStatus = 0;
  165. private static synchronized long nextThreadID() {
  166. return ++threadSeqNumber;
  167. }
  168. /* The object in which this thread is blocked in an interruptible I/O
  169. * operation, if any. The blocker's interrupt method should be invoked
  170. * after setting this thread's interrupt status.
  171. */
  172. private volatile Interruptible blocker;
  173. private Object blockerLock = new Object();
  174. /* Set the blocker field; invoked via reflection magic from java.nio code
  175. */
  176. private void blockedOn(Interruptible b) {
  177. synchronized (blockerLock) {
  178. blocker = b;
  179. }
  180. }
  181. /**
  182. * The minimum priority that a thread can have.
  183. */
  184. public final static int MIN_PRIORITY = 1;
  185. /**
  186. * The default priority that is assigned to a thread.
  187. */
  188. public final static int NORM_PRIORITY = 5;
  189. /**
  190. * The maximum priority that a thread can have.
  191. */
  192. public final static int MAX_PRIORITY = 10;
  193. /**
  194. * Returns a reference to the currently executing thread object.
  195. *
  196. * @return the currently executing thread.
  197. */
  198. public static native Thread currentThread();
  199. /**
  200. * Causes the currently executing thread object to temporarily pause
  201. * and allow other threads to execute.
  202. */
  203. public static native void yield();
  204. /**
  205. * Causes the currently executing thread to sleep (temporarily cease
  206. * execution) for the specified number of milliseconds. The thread
  207. * does not lose ownership of any monitors.
  208. *
  209. * @param millis the length of time to sleep in milliseconds.
  210. * @exception InterruptedException if another thread has interrupted
  211. * the current thread. The <i>interrupted status</i> of the
  212. * current thread is cleared when this exception is thrown.
  213. * @see java.lang.Object#notify()
  214. */
  215. public static native void sleep(long millis) throws InterruptedException;
  216. /**
  217. * Causes the currently executing thread to sleep (cease execution)
  218. * for the specified number of milliseconds plus the specified number
  219. * of nanoseconds. The thread does not lose ownership of any monitors.
  220. *
  221. * @param millis the length of time to sleep in milliseconds.
  222. * @param nanos 0-999999 additional nanoseconds to sleep.
  223. * @exception IllegalArgumentException if the value of millis is
  224. * negative or the value of nanos is not in the range
  225. * 0-999999.
  226. * @exception InterruptedException if another thread has interrupted
  227. * the current thread. The <i>interrupted status</i> of the
  228. * current thread is cleared when this exception is thrown.
  229. * @see java.lang.Object#notify()
  230. */
  231. public static void sleep(long millis, int nanos)
  232. throws InterruptedException {
  233. if (millis < 0) {
  234. throw new IllegalArgumentException("timeout value is negative");
  235. }
  236. if (nanos < 0 || nanos > 999999) {
  237. throw new IllegalArgumentException(
  238. "nanosecond timeout value out of range");
  239. }
  240. if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
  241. millis++;
  242. }
  243. sleep(millis);
  244. }
  245. /**
  246. * Initialize a Thread.
  247. *
  248. * @param g the Thread group
  249. * @param target the object whose run() method gets called
  250. * @param name the name of the new Thread
  251. * @param stackSize the desired stack size for the new thread, or
  252. * zero to indicate that this parameter is to be ignored.
  253. */
  254. private void init(ThreadGroup g, Runnable target, String name,
  255. long stackSize) {
  256. Thread parent = currentThread();
  257. SecurityManager security = System.getSecurityManager();
  258. if (g == null) {
  259. /* Determine if it's an applet or not */
  260. /* If there is a security manager, ask the security manager
  261. what to do. */
  262. if (security != null) {
  263. g = security.getThreadGroup();
  264. }
  265. /* If the security doesn't have a strong opinion of the matter
  266. use the parent thread group. */
  267. if (g == null) {
  268. g = parent.getThreadGroup();
  269. }
  270. }
  271. /* checkAccess regardless of whether or not threadgroup is
  272. explicitly passed in. */
  273. g.checkAccess();
  274. /*
  275. * Do we have the required permissions?
  276. */
  277. if (security != null) {
  278. if (isCCLOverridden(getClass())) {
  279. security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
  280. }
  281. }
  282. g.addUnstarted();
  283. this.group = g;
  284. this.daemon = parent.isDaemon();
  285. this.priority = parent.getPriority();
  286. this.name = name.toCharArray();
  287. if (security == null || isCCLOverridden(parent.getClass()))
  288. this.contextClassLoader = parent.getContextClassLoader();
  289. else
  290. this.contextClassLoader = parent.contextClassLoader;
  291. this.inheritedAccessControlContext = AccessController.getContext();
  292. this.target = target;
  293. setPriority(priority);
  294. if (parent.inheritableThreadLocals != null)
  295. this.inheritableThreadLocals =
  296. ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
  297. /* Stash the specified stack size in case the VM cares */
  298. this.stackSize = stackSize;
  299. /* Set thread ID */
  300. tid = nextThreadID();
  301. }
  302. /**
  303. * Allocates a new <code>Thread</code> object. This constructor has
  304. * the same effect as <code>Thread(null, null,</code>
  305. * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
  306. * a newly generated name. Automatically generated names are of the
  307. * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
  308. *
  309. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  310. * java.lang.Runnable, java.lang.String)
  311. */
  312. public Thread() {
  313. init(null, null, "Thread-" + nextThreadNum(), 0);
  314. }
  315. /**
  316. * Allocates a new <code>Thread</code> object. This constructor has
  317. * the same effect as <code>Thread(null, target,</code>
  318. * <i>gname</i><code>)</code>, where <i>gname</i> is
  319. * a newly generated name. Automatically generated names are of the
  320. * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
  321. *
  322. * @param target the object whose <code>run</code> method is called.
  323. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  324. * java.lang.Runnable, java.lang.String)
  325. */
  326. public Thread(Runnable target) {
  327. init(null, target, "Thread-" + nextThreadNum(), 0);
  328. }
  329. /**
  330. * Allocates a new <code>Thread</code> object. This constructor has
  331. * the same effect as <code>Thread(group, target,</code>
  332. * <i>gname</i><code>)</code>, where <i>gname</i> is
  333. * a newly generated name. Automatically generated names are of the
  334. * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
  335. *
  336. * @param group the thread group.
  337. * @param target the object whose <code>run</code> method is called.
  338. * @exception SecurityException if the current thread cannot create a
  339. * thread in the specified thread group.
  340. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  341. * java.lang.Runnable, java.lang.String)
  342. */
  343. public Thread(ThreadGroup group, Runnable target) {
  344. init(group, target, "Thread-" + nextThreadNum(), 0);
  345. }
  346. /**
  347. * Allocates a new <code>Thread</code> object. This constructor has
  348. * the same effect as <code>Thread(null, null, name)</code>.
  349. *
  350. * @param name the name of the new thread.
  351. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  352. * java.lang.Runnable, java.lang.String)
  353. */
  354. public Thread(String name) {
  355. init(null, null, name, 0);
  356. }
  357. /**
  358. * Allocates a new <code>Thread</code> object. This constructor has
  359. * the same effect as <code>Thread(group, null, name)</code>
  360. *
  361. * @param group the thread group.
  362. * @param name the name of the new thread.
  363. * @exception SecurityException if the current thread cannot create a
  364. * thread in the specified thread group.
  365. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  366. * java.lang.Runnable, java.lang.String)
  367. */
  368. public Thread(ThreadGroup group, String name) {
  369. init(group, null, name, 0);
  370. }
  371. /**
  372. * Allocates a new <code>Thread</code> object. This constructor has
  373. * the same effect as <code>Thread(null, target, name)</code>.
  374. *
  375. * @param target the object whose <code>run</code> method is called.
  376. * @param name the name of the new thread.
  377. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  378. * java.lang.Runnable, java.lang.String)
  379. */
  380. public Thread(Runnable target, String name) {
  381. init(null, target, name, 0);
  382. }
  383. /**
  384. * Allocates a new <code>Thread</code> object so that it has
  385. * <code>target</code> as its run object, has the specified
  386. * <code>name</code> as its name, and belongs to the thread group
  387. * referred to by <code>group</code>.
  388. * <p>
  389. * If <code>group</code> is <code>null</code> and there is a
  390. * security manager, the group is determined by the security manager's
  391. * <code>getThreadGroup</code> method. If <code>group</code> is
  392. * <code>null</code> and there is not a security manager, or the
  393. * security manager's <code>getThreadGroup</code> method returns
  394. * <code>null</code>, the group is set to be the same ThreadGroup
  395. * as the thread that is creating the new thread.
  396. *
  397. * <p>If there is a security manager, its <code>checkAccess</code>
  398. * method is called with the ThreadGroup as its argument.
  399. * <p>In addition, its <code>checkPermission</code>
  400. * method is called with the
  401. * <code>RuntimePermission("enableContextClassLoaderOverride")</code>
  402. * permission when invoked directly or indirectly by the constructor
  403. * of a subclass which overrides the <code>getContextClassLoader</code>
  404. * or <code>setContextClassLoader</code> methods.
  405. * This may result in a SecurityException.
  406. * <p>
  407. * If the <code>target</code> argument is not <code>null</code>, the
  408. * <code>run</code> method of the <code>target</code> is called when
  409. * this thread is started. If the target argument is
  410. * <code>null</code>, this thread's <code>run</code> method is called
  411. * when this thread is started.
  412. * <p>
  413. * The priority of the newly created thread is set equal to the
  414. * priority of the thread creating it, that is, the currently running
  415. * thread. The method <code>setPriority</code> may be used to
  416. * change the priority to a new value.
  417. * <p>
  418. * The newly created thread is initially marked as being a daemon
  419. * thread if and only if the thread creating it is currently marked
  420. * as a daemon thread. The method <code>setDaemon </code> may be used
  421. * to change whether or not a thread is a daemon.
  422. *
  423. * @param group the thread group.
  424. * @param target the object whose <code>run</code> method is called.
  425. * @param name the name of the new thread.
  426. * @exception SecurityException if the current thread cannot create a
  427. * thread in the specified thread group or cannot
  428. * override the context class loader methods.
  429. * @see java.lang.Runnable#run()
  430. * @see java.lang.Thread#run()
  431. * @see java.lang.Thread#setDaemon(boolean)
  432. * @see java.lang.Thread#setPriority(int)
  433. * @see java.lang.ThreadGroup#checkAccess()
  434. * @see SecurityManager#checkAccess
  435. */
  436. public Thread(ThreadGroup group, Runnable target, String name) {
  437. init(group, target, name, 0);
  438. }
  439. /**
  440. * Allocates a new <code>Thread</code> object so that it has
  441. * <code>target</code> as its run object, has the specified
  442. * <code>name</code> as its name, belongs to the thread group referred to
  443. * by <code>group</code>, and has the specified <i>stack size</i>.
  444. *
  445. * <p>This constructor is identical to {@link
  446. * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact
  447. * that it allows the thread stack size to be specified. The stack size
  448. * is the approximate number of bytes of address space that the virtual
  449. * machine is to allocate for this thread's stack. <b>The effect of the
  450. * <tt>stackSize</tt> parameter, if any, is highly platform dependent.</b>
  451. *
  452. * <p>On some platforms, specifying a higher value for the
  453. * <tt>stackSize</tt> parameter may allow a thread to achieve greater
  454. * recursion depth before throwing a {@link StackOverflowError}.
  455. * Similarly, specifying a lower value may allow a greater number of
  456. * threads to exist concurrently without throwing an {@link
  457. * OutOfMemoryError} (or other internal error). The details of
  458. * the relationship between the value of the <tt>stackSize</tt> parameter
  459. * and the maximum recursion depth and concurrency level are
  460. * platform-dependent. <b>On some platforms, the value of the
  461. * <tt>stackSize</tt> parameter may have no effect whatsoever.</b>
  462. *
  463. * <p>The virtual machine is free to treat the <tt>stackSize</tt>
  464. * parameter as a suggestion. If the specified value is unreasonably low
  465. * for the platform, the virtual machine may instead use some
  466. * platform-specific minimum value; if the specified value is unreasonably
  467. * high, the virtual machine may instead use some platform-specific
  468. * maximum. Likewise, the virtual machine is free to round the specified
  469. * value up or down as it sees fit (or to ignore it completely).
  470. *
  471. * <p>Specifying a value of zero for the <tt>stackSize</tt> parameter will
  472. * cause this constructor to behave exactly like the
  473. * <tt>Thread(ThreadGroup, Runnable, String)</tt> constructor.
  474. *
  475. * <p><i>Due to the platform-dependent nature of the behavior of this
  476. * constructor, extreme care should be exercised in its use.
  477. * The thread stack size necessary to perform a given computation will
  478. * likely vary from one JRE implementation to another. In light of this
  479. * variation, careful tuning of the stack size parameter may be required,
  480. * and the tuning may need to be repeated for each JRE implementation on
  481. * which an application is to run.</i>
  482. *
  483. * <p>Implementation note: Java platform implementers are encouraged to
  484. * document their implementation's behavior with respect to the
  485. * <tt>stackSize parameter</tt>.
  486. *
  487. * @param group the thread group.
  488. * @param target the object whose <code>run</code> method is called.
  489. * @param name the name of the new thread.
  490. * @param stackSize the desired stack size for the new thread, or
  491. * zero to indicate that this parameter is to be ignored.
  492. * @exception SecurityException if the current thread cannot create a
  493. * thread in the specified thread group.
  494. */
  495. public Thread(ThreadGroup group, Runnable target, String name,
  496. long stackSize) {
  497. init(group, target, name, stackSize);
  498. }
  499. /**
  500. * Causes this thread to begin execution; the Java Virtual Machine
  501. * calls the <code>run</code> method of this thread.
  502. * <p>
  503. * The result is that two threads are running concurrently: the
  504. * current thread (which returns from the call to the
  505. * <code>start</code> method) and the other thread (which executes its
  506. * <code>run</code> method).
  507. * <p>
  508. * It is never legal to start a thread more than once.
  509. * In particular, a thread may not be restarted once it has completed
  510. * execution.
  511. *
  512. * @exception IllegalThreadStateException if the thread was already
  513. * started.
  514. * @see java.lang.Thread#run()
  515. * @see java.lang.Thread#stop()
  516. */
  517. public synchronized void start() {
  518. if (started)
  519. throw new IllegalThreadStateException();
  520. started = true;
  521. group.add(this);
  522. start0();
  523. }
  524. private native void start0();
  525. /**
  526. * If this thread was constructed using a separate
  527. * <code>Runnable</code> run object, then that
  528. * <code>Runnable</code> object's <code>run</code> method is called;
  529. * otherwise, this method does nothing and returns.
  530. * <p>
  531. * Subclasses of <code>Thread</code> should override this method.
  532. *
  533. * @see java.lang.Thread#start()
  534. * @see java.lang.Thread#stop()
  535. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  536. * java.lang.Runnable, java.lang.String)
  537. * @see java.lang.Runnable#run()
  538. */
  539. public void run() {
  540. if (target != null) {
  541. target.run();
  542. }
  543. }
  544. /**
  545. * This method is called by the system to give a Thread
  546. * a chance to clean up before it actually exits.
  547. */
  548. private void exit() {
  549. if (group != null) {
  550. group.remove(this);
  551. group = null;
  552. }
  553. /* Aggressively null out all reference fields: see bug 4006245 */
  554. target = null;
  555. /* Speed the release of some of these resources */
  556. threadLocals = null;
  557. inheritableThreadLocals = null;
  558. inheritedAccessControlContext = null;
  559. blocker = null;
  560. uncaughtExceptionHandler = null;
  561. }
  562. /**
  563. * Forces the thread to stop executing.
  564. * <p>
  565. * If there is a security manager installed, its <code>checkAccess</code>
  566. * method is called with <code>this</code>
  567. * as its argument. This may result in a
  568. * <code>SecurityException</code> being raised (in the current thread).
  569. * <p>
  570. * If this thread is different from the current thread (that is, the current
  571. * thread is trying to stop a thread other than itself), the
  572. * security manager's <code>checkPermission</code> method (with a
  573. * <code>RuntimePermission("stopThread")</code> argument) is called in
  574. * addition.
  575. * Again, this may result in throwing a
  576. * <code>SecurityException</code> (in the current thread).
  577. * <p>
  578. * The thread represented by this thread is forced to stop whatever
  579. * it is doing abnormally and to throw a newly created
  580. * <code>ThreadDeath</code> object as an exception.
  581. * <p>
  582. * It is permitted to stop a thread that has not yet been started.
  583. * If the thread is eventually started, it immediately terminates.
  584. * <p>
  585. * An application should not normally try to catch
  586. * <code>ThreadDeath</code> unless it must do some extraordinary
  587. * cleanup operation (note that the throwing of
  588. * <code>ThreadDeath</code> causes <code>finally</code> clauses of
  589. * <code>try</code> statements to be executed before the thread
  590. * officially dies). If a <code>catch</code> clause catches a
  591. * <code>ThreadDeath</code> object, it is important to rethrow the
  592. * object so that the thread actually dies.
  593. * <p>
  594. * The top-level error handler that reacts to otherwise uncaught
  595. * exceptions does not print out a message or otherwise notify the
  596. * application if the uncaught exception is an instance of
  597. * <code>ThreadDeath</code>.
  598. *
  599. * @exception SecurityException if the current thread cannot
  600. * modify this thread.
  601. * @see java.lang.Thread#interrupt()
  602. * @see java.lang.Thread#checkAccess()
  603. * @see java.lang.Thread#run()
  604. * @see java.lang.Thread#start()
  605. * @see java.lang.ThreadDeath
  606. * @see java.lang.ThreadGroup#uncaughtException(java.lang.Thread,
  607. * java.lang.Throwable)
  608. * @see SecurityManager#checkAccess(Thread)
  609. * @see SecurityManager#checkPermission
  610. * @deprecated This method is inherently unsafe. Stopping a thread with
  611. * Thread.stop causes it to unlock all of the monitors that it
  612. * has locked (as a natural consequence of the unchecked
  613. * <code>ThreadDeath</code> exception propagating up the stack). If
  614. * any of the objects previously protected by these monitors were in
  615. * an inconsistent state, the damaged objects become visible to
  616. * other threads, potentially resulting in arbitrary behavior. Many
  617. * uses of <code>stop</code> should be replaced by code that simply
  618. * modifies some variable to indicate that the target thread should
  619. * stop running. The target thread should check this variable
  620. * regularly, and return from its run method in an orderly fashion
  621. * if the variable indicates that it is to stop running. If the
  622. * target thread waits for long periods (on a condition variable,
  623. * for example), the <code>interrupt</code> method should be used to
  624. * interrupt the wait.
  625. * For more information, see
  626. * <a href="{@docRoot}/../guide/misc/threadPrimitiveDeprecation.html">Why
  627. * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  628. */
  629. @Deprecated
  630. public final void stop() {
  631. synchronized (this) {
  632. //if the thread is already dead, return
  633. if (!this.isAlive()) return;
  634. SecurityManager security = System.getSecurityManager();
  635. if (security != null) {
  636. checkAccess();
  637. if (this != Thread.currentThread()) {
  638. security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
  639. }
  640. }
  641. resume(); // Wake up thread if it was suspended; no-op otherwise
  642. stop0(new ThreadDeath());
  643. }
  644. }
  645. /**
  646. * Forces the thread to stop executing.
  647. * <p>
  648. * If there is a security manager installed, the <code>checkAccess</code>
  649. * method of this thread is called, which may result in a
  650. * <code>SecurityException</code> being raised (in the current thread).
  651. * <p>
  652. * If this thread is different from the current thread (that is, the current
  653. * thread is trying to stop a thread other than itself) or
  654. * <code>obj</code> is not an instance of <code>ThreadDeath</code>, the
  655. * security manager's <code>checkPermission</code> method (with the
  656. * <code>RuntimePermission("stopThread")</code> argument) is called in
  657. * addition.
  658. * Again, this may result in throwing a
  659. * <code>SecurityException</code> (in the current thread).
  660. * <p>
  661. * If the argument <code>obj</code> is null, a
  662. * <code>NullPointerException</code> is thrown (in the current thread).
  663. * <p>
  664. * The thread represented by this thread is forced to complete
  665. * whatever it is doing abnormally and to throw the
  666. * <code>Throwable</code> object <code>obj</code> as an exception. This
  667. * is an unusual action to take; normally, the <code>stop</code> method
  668. * that takes no arguments should be used.
  669. * <p>
  670. * It is permitted to stop a thread that has not yet been started.
  671. * If the thread is eventually started, it immediately terminates.
  672. *
  673. * @param obj the Throwable object to be thrown.
  674. * @exception SecurityException if the current thread cannot modify
  675. * this thread.
  676. * @see java.lang.Thread#interrupt()
  677. * @see java.lang.Thread#checkAccess()
  678. * @see java.lang.Thread#run()
  679. * @see java.lang.Thread#start()
  680. * @see java.lang.Thread#stop()
  681. * @see SecurityManager#checkAccess(Thread)
  682. * @see SecurityManager#checkPermission
  683. * @deprecated This method is inherently unsafe. See {@link #stop()}
  684. * for details. An additional danger of this
  685. * method is that it may be used to generate exceptions that the
  686. * target thread is unprepared to handle (including checked
  687. * exceptions that the thread could not possibly throw, were it
  688. * not for this method).
  689. * For more information, see
  690. * <a href="{@docRoot}/../guide/misc/threadPrimitiveDeprecation.html">Why
  691. * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  692. */
  693. @Deprecated
  694. public final synchronized void stop(Throwable obj) {
  695. SecurityManager security = System.getSecurityManager();
  696. if (security != null) {
  697. checkAccess();
  698. if ((this != Thread.currentThread()) ||
  699. (!(obj instanceof ThreadDeath))) {
  700. security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
  701. }
  702. }
  703. resume(); // Wake up thread if it was suspended; no-op otherwise
  704. stop0(obj);
  705. }
  706. /**
  707. * Interrupts this thread.
  708. *
  709. * <p> Unless the current thread is interrupting itself, which is
  710. * always permitted, the {@link #checkAccess() checkAccess} method
  711. * of this thread is invoked, which may cause a {@link
  712. * SecurityException} to be thrown.
  713. *
  714. * <p> If this thread is blocked in an invocation of the {@link
  715. * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
  716. * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
  717. * class, or of the {@link #join()}, {@link #join(long)}, {@link
  718. * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
  719. * methods of this class, then its interrupt status will be cleared and it
  720. * will receive an {@link InterruptedException}.
  721. *
  722. * <p> If this thread is blocked in an I/O operation upon an {@link
  723. * java.nio.channels.InterruptibleChannel </code>interruptible
  724. * channel<code>} then the channel will be closed, the thread's interrupt
  725. * status will be set, and the thread will receive a {@link
  726. * java.nio.channels.ClosedByInterruptException}.
  727. *
  728. * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
  729. * then the thread's interrupt status will be set and it will return
  730. * immediately from the selection operation, possibly with a non-zero
  731. * value, just as if the selector's {@link
  732. * java.nio.channels.Selector#wakeup wakeup} method were invoked.
  733. *
  734. * <p> If none of the previous conditions hold then this thread's interrupt
  735. * status will be set. </p>
  736. *
  737. * @throws SecurityException
  738. * if the current thread cannot modify this thread
  739. *
  740. * @revised 1.4
  741. * @spec JSR-51
  742. */
  743. public void interrupt() {
  744. if (this != Thread.currentThread())
  745. checkAccess();
  746. synchronized (blockerLock) {
  747. Interruptible b = blocker;
  748. if (b != null) {
  749. interrupt0(); // Just to set the interrupt flag
  750. b.interrupt();
  751. return;
  752. }
  753. }
  754. interrupt0();
  755. }
  756. /**
  757. * Tests whether the current thread has been interrupted. The
  758. * <i>interrupted status</i> of the thread is cleared by this method. In
  759. * other words, if this method were to be called twice in succession, the
  760. * second call would return false (unless the current thread were
  761. * interrupted again, after the first call had cleared its interrupted
  762. * status and before the second call had examined it).
  763. *
  764. * @return <code>true</code> if the current thread has been interrupted;
  765. * <code>false</code> otherwise.
  766. * @see java.lang.Thread#isInterrupted()
  767. */
  768. public static boolean interrupted() {
  769. return currentThread().isInterrupted(true);
  770. }
  771. /**
  772. * Tests whether this thread has been interrupted. The <i>interrupted
  773. * status</i> of the thread is unaffected by this method.
  774. *
  775. * @return <code>true</code> if this thread has been interrupted;
  776. * <code>false</code> otherwise.
  777. * @see java.lang.Thread#interrupted()
  778. */
  779. public boolean isInterrupted() {
  780. return isInterrupted(false);
  781. }
  782. /**
  783. * Tests if some Thread has been interrupted. The interrupted state
  784. * is reset or not based on the value of ClearInterrupted that is
  785. * passed.
  786. */
  787. private native boolean isInterrupted(boolean ClearInterrupted);
  788. /**
  789. * Throws {@link NoSuchMethodError}.
  790. *
  791. * @deprecated This method was originally designed to destroy this
  792. * thread without any cleanup. Any monitors it held would have
  793. * remained locked. However, the method was never implemented.
  794. * If if were to be implemented, it would be deadlock-prone in
  795. * much the manner of {@link #suspend}. If the target thread held
  796. * a lock protecting a critical system resource when it was
  797. * destroyed, no thread could ever access this resource again.
  798. * If another thread ever attempted to lock this resource, deadlock
  799. * would result. Such deadlocks typically manifest themselves as
  800. * "frozen" processes. For more information, see
  801. * <a href="{@docRoot}/../guide/misc/threadPrimitiveDeprecation.html">
  802. * Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  803. * @throws NoSuchMethodError always
  804. */
  805. @Deprecated
  806. public void destroy() {
  807. throw new NoSuchMethodError();
  808. }
  809. /**
  810. * Tests if this thread is alive. A thread is alive if it has
  811. * been started and has not yet died.
  812. *
  813. * @return <code>true</code> if this thread is alive;
  814. * <code>false</code> otherwise.
  815. */
  816. public final native boolean isAlive();
  817. /**
  818. * Suspends this thread.
  819. * <p>
  820. * First, the <code>checkAccess</code> method of this thread is called
  821. * with no arguments. This may result in throwing a
  822. * <code>SecurityException </code>(in the current thread).
  823. * <p>
  824. * If the thread is alive, it is suspended and makes no further
  825. * progress unless and until it is resumed.
  826. *
  827. * @exception SecurityException if the current thread cannot modify
  828. * this thread.
  829. * @see #checkAccess
  830. * @deprecated This method has been deprecated, as it is
  831. * inherently deadlock-prone. If the target thread holds a lock on the
  832. * monitor protecting a critical system resource when it is suspended, no
  833. * thread can access this resource until the target thread is resumed. If
  834. * the thread that would resume the target thread attempts to lock this
  835. * monitor prior to calling <code>resume</code>, deadlock results. Such
  836. * deadlocks typically manifest themselves as "frozen" processes.
  837. * For more information, see
  838. * <a href="{@docRoot}/../guide/misc/threadPrimitiveDeprecation.html">Why
  839. * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  840. */
  841. @Deprecated
  842. public final void suspend() {
  843. checkAccess();
  844. suspend0();
  845. }
  846. /**
  847. * Resumes a suspended thread.
  848. * <p>
  849. * First, the <code>checkAccess</code> method of this thread is called
  850. * with no arguments. This may result in throwing a
  851. * <code>SecurityException</code> (in the current thread).
  852. * <p>
  853. * If the thread is alive but suspended, it is resumed and is
  854. * permitted to make progress in its execution.
  855. *
  856. * @exception SecurityException if the current thread cannot modify this
  857. * thread.
  858. * @see #checkAccess
  859. * @see java.lang.Thread#suspend()
  860. * @deprecated This method exists solely for use with {@link #suspend},
  861. * which has been deprecated because it is deadlock-prone.
  862. * For more information, see
  863. * <a href="{@docRoot}/../guide/misc/threadPrimitiveDeprecation.html">Why
  864. * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  865. */
  866. @Deprecated
  867. public final void resume() {
  868. checkAccess();
  869. resume0();
  870. }
  871. /**
  872. * Changes the priority of this thread.
  873. * <p>
  874. * First the <code>checkAccess</code> method of this thread is called
  875. * with no arguments. This may result in throwing a
  876. * <code>SecurityException</code>.
  877. * <p>
  878. * Otherwise, the priority of this thread is set to the smaller of
  879. * the specified <code>newPriority</code> and the maximum permitted
  880. * priority of the thread's thread group.
  881. *
  882. * @param newPriority priority to set this thread to
  883. * @exception IllegalArgumentException If the priority is not in the
  884. * range <code>MIN_PRIORITY</code> to
  885. * <code>MAX_PRIORITY</code>.
  886. * @exception SecurityException if the current thread cannot modify
  887. * this thread.
  888. * @see #getPriority
  889. * @see java.lang.Thread#checkAccess()
  890. * @see java.lang.Thread#getPriority()
  891. * @see java.lang.Thread#getThreadGroup()
  892. * @see java.lang.Thread#MAX_PRIORITY
  893. * @see java.lang.Thread#MIN_PRIORITY
  894. * @see java.lang.ThreadGroup#getMaxPriority()
  895. */
  896. public final void setPriority(int newPriority) {
  897. checkAccess();
  898. if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
  899. throw new IllegalArgumentException();
  900. }
  901. if (newPriority > group.getMaxPriority()) {
  902. newPriority = group.getMaxPriority();
  903. }
  904. setPriority0(priority = newPriority);
  905. }
  906. /**
  907. * Returns this thread's priority.
  908. *
  909. * @return this thread's priority.
  910. * @see #setPriority
  911. * @see java.lang.Thread#setPriority(int)
  912. */
  913. public final int getPriority() {
  914. return priority;
  915. }
  916. /**
  917. * Changes the name of this thread to be equal to the argument
  918. * <code>name</code>.
  919. * <p>
  920. * First the <code>checkAccess</code> method of this thread is called
  921. * with no arguments. This may result in throwing a
  922. * <code>SecurityException</code>.
  923. *
  924. * @param name the new name for this thread.
  925. * @exception SecurityException if the current thread cannot modify this
  926. * thread.
  927. * @see #getName
  928. * @see java.lang.Thread#checkAccess()
  929. * @see java.lang.Thread#getName()
  930. */
  931. public final void setName(String name) {
  932. checkAccess();
  933. this.name = name.toCharArray();
  934. }
  935. /**
  936. * Returns this thread's name.
  937. *
  938. * @return this thread's name.
  939. * @see #setName
  940. * @see java.lang.Thread#setName(java.lang.String)
  941. */
  942. public final String getName() {
  943. return String.valueOf(name);
  944. }
  945. /**
  946. * Returns the thread group to which this thread belongs.
  947. * This method returns null if this thread has died
  948. * (been stopped).
  949. *
  950. * @return this thread's thread group.
  951. */
  952. public final ThreadGroup getThreadGroup() {
  953. return group;
  954. }
  955. /**
  956. * Returns the number of active threads in the current thread's thread
  957. * group.
  958. *
  959. * @return the number of active threads in the current thread's thread
  960. * group.
  961. */
  962. public static int activeCount() {
  963. return currentThread().getThreadGroup().activeCount();
  964. }
  965. /**
  966. * Copies into the specified array every active thread in
  967. * the current thread's thread group and its subgroups. This method simply
  968. * calls the <code>enumerate</code> method of the current thread's thread
  969. * group with the array argument.
  970. * <p>
  971. * First, if there is a security manager, that <code>enumerate</code>
  972. * method calls the security
  973. * manager's <code>checkAccess</code> method
  974. * with the thread group as its argument. This may result
  975. * in throwing a <code>SecurityException</code>.
  976. *
  977. * @param tarray an array of Thread objects to copy to
  978. * @return the number of threads put into the array
  979. * @exception SecurityException if a security manager exists and its
  980. * <code>checkAccess</code> method doesn't allow the operation.
  981. * @see java.lang.ThreadGroup#enumerate(java.lang.Thread[])
  982. * @see java.lang.SecurityManager#checkAccess(java.lang.ThreadGroup)
  983. */
  984. public static int enumerate(Thread tarray[]) {
  985. return currentThread().getThreadGroup().enumerate(tarray);
  986. }
  987. /**
  988. * Counts the number of stack frames in this thread. The thread must
  989. * be suspended.
  990. *
  991. * @return the number of stack frames in this thread.
  992. * @exception IllegalThreadStateException if this thread is not
  993. * suspended.
  994. * @deprecated The definition of this call depends on {@link #suspend},
  995. * which is deprecated. Further, the results of this call
  996. * were never well-defined.
  997. */
  998. @Deprecated
  999. public native int countStackFrames();
  1000. /**
  1001. * Waits at most <code>millis</code> milliseconds for this thread to
  1002. * die. A timeout of <code>0</code> means to wait forever.
  1003. *
  1004. * @param millis the time to wait in milliseconds.
  1005. * @exception InterruptedException if another thread has interrupted
  1006. * the current thread. The <i>interrupted status</i> of the
  1007. * current thread is cleared when this exception is thrown.
  1008. */
  1009. public final synchronized void join(long millis)
  1010. throws InterruptedException {
  1011. long base = System.currentTimeMillis();
  1012. long now = 0;
  1013. if (millis < 0) {
  1014. throw new IllegalArgumentException("timeout value is negative");
  1015. }
  1016. if (millis == 0) {
  1017. while (isAlive()) {
  1018. wait(0);
  1019. }
  1020. } else {
  1021. while (isAlive()) {
  1022. long delay = millis - now;
  1023. if (delay <= 0) {
  1024. break;
  1025. }
  1026. wait(delay);
  1027. now = System.currentTimeMillis() - base;
  1028. }
  1029. }
  1030. }
  1031. /**
  1032. * Waits at most <code>millis</code> milliseconds plus
  1033. * <code>nanos</code> nanoseconds for this thread to die.
  1034. *
  1035. * @param millis the time to wait in milliseconds.
  1036. * @param nanos 0-999999 additional nanoseconds to wait.
  1037. * @exception IllegalArgumentException if the value of millis is negative
  1038. * the value of nanos is not in the range 0-999999.
  1039. * @exception InterruptedException if another thread has interrupted
  1040. * the current thread. The <i>interrupted status</i> of the
  1041. * current thread is cleared when this exception is thrown.
  1042. */
  1043. public final synchronized void join(long millis, int nanos)
  1044. throws InterruptedException {
  1045. if (millis < 0) {
  1046. throw new IllegalArgumentException("timeout value is negative");
  1047. }
  1048. if (nanos < 0 || nanos > 999999) {
  1049. throw new IllegalArgumentException(
  1050. "nanosecond timeout value out of range");
  1051. }
  1052. if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
  1053. millis++;
  1054. }
  1055. join(millis);
  1056. }
  1057. /**
  1058. * Waits for this thread to die.
  1059. *
  1060. * @exception InterruptedException if another thread has interrupted
  1061. * the current thread. The <i>interrupted status</i> of the
  1062. * current thread is cleared when this exception is thrown.
  1063. */
  1064. public final void join() throws InterruptedException {
  1065. join(0);
  1066. }
  1067. /**
  1068. * Prints a stack trace of the current thread. This method is used
  1069. * only for debugging.
  1070. *
  1071. * @see java.lang.Throwable#printStackTrace()
  1072. */
  1073. public static void dumpStack() {
  1074. new Exception("Stack trace").printStackTrace();
  1075. }
  1076. /**
  1077. * Marks this thread as either a daemon thread or a user thread. The
  1078. * Java Virtual Machine exits when the only threads running are all
  1079. * daemon threads.
  1080. * <p>
  1081. * This method must be called before the thread is started.
  1082. * <p>
  1083. * This method first calls the <code>checkAccess</code> method
  1084. * of this thread
  1085. * with no arguments. This may result in throwing a
  1086. * <code>SecurityException </code>(in the current thread).
  1087. *
  1088. * @param on if <code>true</code>, marks this thread as a
  1089. * daemon thread.
  1090. * @exception IllegalThreadStateException if this thread is active.
  1091. * @exception SecurityException if the current thread cannot modify
  1092. * this thread.
  1093. * @see java.lang.Thread#isDaemon()
  1094. * @see #checkAccess
  1095. */
  1096. public final void setDaemon(boolean on) {
  1097. checkAccess();
  1098. if (isAlive()) {
  1099. throw new IllegalThreadStateException();
  1100. }
  1101. daemon = on;
  1102. }
  1103. /**
  1104. * Tests if this thread is a daemon thread.
  1105. *
  1106. * @return <code>true</code> if this thread is a daemon thread;
  1107. * <code>false</code> otherwise.
  1108. * @see java.lang.Thread#setDaemon(boolean)
  1109. */
  1110. public final boolean isDaemon() {
  1111. return daemon;
  1112. }
  1113. /**
  1114. * Determines if the currently running thread has permission to
  1115. * modify this thread.
  1116. * <p>
  1117. * If there is a security manager, its <code>checkAccess</code> method
  1118. * is called with this thread as its argument. This may result in
  1119. * throwing a <code>SecurityException</code>.
  1120. * <p>
  1121. * Note: This method was mistakenly non-final in JDK 1.1.
  1122. * It has been made final in the Java 2 Platform.
  1123. *
  1124. * @exception SecurityException if the current thread is not allowed to
  1125. * access this thread.
  1126. * @see java.lang.SecurityManager#checkAccess(java.lang.Thread)
  1127. */
  1128. public final void checkAccess() {
  1129. SecurityManager security = System.getSecurityManager();
  1130. if (security != null) {
  1131. security.checkAccess(this);
  1132. }
  1133. }
  1134. /**
  1135. * Returns a string representation of this thread, including the
  1136. * thread's name, priority, and thread group.
  1137. *
  1138. * @return a string representation of this thread.
  1139. */
  1140. public String toString() {
  1141. ThreadGroup group = getThreadGroup();
  1142. if (group != null) {
  1143. return "Thread[" + getName() + "," + getPriority() + "," +
  1144. group.getName() + "]";
  1145. } else {
  1146. return "Thread[" + getName() + "," + getPriority() + "," +
  1147. "" + "]";
  1148. }
  1149. }
  1150. /**
  1151. * Returns the context ClassLoader for this Thread. The context
  1152. * ClassLoader is provided by the creator of the thread for use
  1153. * by code running in this thread when loading classes and resources.
  1154. * If not set, the default is the ClassLoader context of the parent
  1155. * Thread. The context ClassLoader of the primordial thread is
  1156. * typically set to the class loader used to load the application.
  1157. *
  1158. * <p>First, if there is a security manager, and the caller's class
  1159. * loader is not null and the caller's class loader is not the same as or
  1160. * an ancestor of the context class loader for the thread whose
  1161. * context class loader is being requested, then the security manager's
  1162. * <code>checkPermission</code>
  1163. * method is called with a
  1164. * <code>RuntimePermission("getClassLoader")</code> permission
  1165. * to see if it's ok to get the context ClassLoader..
  1166. *
  1167. * @return the context ClassLoader for this Thread
  1168. *
  1169. * @throws SecurityException
  1170. * if a security manager exists and its
  1171. * <code>checkPermission</code> method doesn't allow
  1172. * getting the context ClassLoader.
  1173. * @see #setContextClassLoader
  1174. * @see SecurityManager#checkPermission
  1175. * @see java.lang.RuntimePermission
  1176. *
  1177. * @since 1.2
  1178. */
  1179. public ClassLoader getContextClassLoader() {
  1180. if (contextClassLoader == null)
  1181. return null;
  1182. SecurityManager sm = System.getSecurityManager();
  1183. if (sm != null) {
  1184. ClassLoader ccl = ClassLoader.getCallerClassLoader();
  1185. if (ccl != null && ccl != contextClassLoader &&
  1186. !contextClassLoader.isAncestor(ccl)) {
  1187. sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
  1188. }
  1189. }
  1190. return contextClassLoader;
  1191. }
  1192. /**
  1193. * Sets the context ClassLoader for this Thread. The context
  1194. * ClassLoader can be set when a thread is created, and allows
  1195. * the creator of the thread to provide the appropriate class loader
  1196. * to code running in the thread when loading classes and resources.
  1197. *
  1198. * <p>First, if there is a security manager, its <code>checkPermission</code>
  1199. * method is called with a
  1200. * <code>RuntimePermission("setContextClassLoader")</code> permission
  1201. * to see if it's ok to set the context ClassLoader..
  1202. *
  1203. * @param cl the context ClassLoader for this Thread
  1204. *
  1205. * @exception SecurityException if the current thread cannot set the
  1206. * context ClassLoader.
  1207. * @see #getContextClassLoader
  1208. * @see SecurityManager#checkPermission
  1209. * @see java.lang.RuntimePermission
  1210. *
  1211. * @since 1.2
  1212. */
  1213. public void setContextClassLoader(ClassLoader cl) {
  1214. SecurityManager sm = System.getSecurityManager();
  1215. if (sm != null) {
  1216. sm.checkPermission(new RuntimePermission("setContextClassLoader"));
  1217. }
  1218. contextClassLoader = cl;
  1219. }
  1220. /**
  1221. * Returns <tt>true</tt> if and only if the current thread holds the
  1222. * monitor lock on the specified object.
  1223. *
  1224. * <p>This method is designed to allow a program to assert that
  1225. * the current thread already holds a specified lock:
  1226. * <pre>
  1227. * assert Thread.holdsLock(obj);
  1228. * </pre>
  1229. *
  1230. * @param obj the object on which to test lock ownership
  1231. * @throws NullPointerException if obj is <tt>null</tt>
  1232. * @return <tt>true</tt> if the current thread holds the monitor lock on
  1233. * the specified object.
  1234. * @since 1.4
  1235. */
  1236. public static native boolean holdsLock(Object obj);
  1237. private static final StackTraceElement[] EMPTY_STACK_TRACE
  1238. = new StackTraceElement[0];
  1239. /**
  1240. * Returns an array of stack trace elements representing the stack dump
  1241. * of this thread. This method will return a zero-length array if
  1242. * this thread has not started or has terminated.
  1243. * If the returned array is of non-zero length then the first element of
  1244. * the array represents the top of the stack, which is the most recent
  1245. * method invocation in the sequence. The last element of the array
  1246. * represents the bottom of the stack, which is the least recent method
  1247. * invocation in the sequence.
  1248. *
  1249. * <p>If there is a security manager, and this thread is not
  1250. * the current thread, then the security manager's
  1251. * <tt>checkPermission</tt> method is called with a
  1252. * <tt>RuntimePermission("getStackTrace")</tt> permission
  1253. * to see if it's ok to get the stack trace.
  1254. *
  1255. * <p>Some virtual machines may, under some circumstances, omit one
  1256. * or more stack frames from the stack trace. In the extreme case,
  1257. * a virtual machine that has no stack trace information concerning
  1258. * this thread is permitted to return a zero-length array from this
  1259. * method.
  1260. *
  1261. * @return an array of <tt>StackTraceElement</tt>,
  1262. * each represents one stack frame.
  1263. *
  1264. * @throws SecurityException
  1265. * if a security manager exists and its
  1266. * <tt>checkPermission</tt> method doesn't allow
  1267. * getting the stack trace of thread.
  1268. * @see SecurityManager#checkPermission
  1269. * @see java.lang.RuntimePermission
  1270. * @see Throwable#getStackTrace
  1271. *
  1272. * @since 1.5
  1273. */
  1274. public StackTraceElement[] getStackTrace() {
  1275. if (this != Thread.currentThread()) {
  1276. // check for getStackTrace permission
  1277. SecurityManager security = System.getSecurityManager();
  1278. if (security != null) {
  1279. security.checkPermission(
  1280. SecurityConstants.GET_STACK_TRACE_PERMISSION);
  1281. }
  1282. }
  1283. if (!isAlive()) {
  1284. return EMPTY_STACK_TRACE;
  1285. }
  1286. Thread[] threads = new Thread[1];
  1287. threads[0] = this;
  1288. StackTraceElement[][] result = dumpThreads(threads);
  1289. return result[0];
  1290. }
  1291. /**
  1292. * Returns a map of stack traces for all live threads.
  1293. * The map keys are threads and each map value is an array of
  1294. * <tt>StackTraceElement</tt> that represents the stack dump
  1295. * of the corresponding <tt>Thread</tt>.
  1296. * The returned stack traces are in the format specified for
  1297. * the {@link #getStackTrace getStackTrace} method.
  1298. *
  1299. * <p>The threads may be executing while this method is called.
  1300. * The stack trace of each thread only represents a snapshot and
  1301. * each stack trace may be obtained at different time. A zero-length
  1302. * array will be returned in the map value if the virtual machine has
  1303. * no stack trace information about a thread.
  1304. *
  1305. * <p>If there is a security manager, then the security manager's
  1306. * <tt>checkPermission</tt> method is called with a
  1307. * <tt>RuntimePermission("getStackTrace")</tt> permission as well as
  1308. * <tt>RuntimePermission("modifyThreadGroup")</tt> permission
  1309. * to see if it is ok to get the stack trace of all threads.
  1310. *
  1311. * @return a <tt>Map</tt> from <tt>Thread</tt> to an array of
  1312. * <tt>StackTraceElement</tt> that represents the stack trace of
  1313. * the corresponding thread.
  1314. *
  1315. * @throws SecurityException
  1316. * if a security manager exists and its
  1317. * <tt>checkPermission</tt> method doesn't allow
  1318. * getting the stack trace of thread.
  1319. * @see #getStackTrace
  1320. * @see SecurityManager#checkPermission
  1321. * @see java.lang.RuntimePermission
  1322. * @see Throwable#getStackTrace
  1323. *
  1324. * @since 1.5
  1325. */
  1326. public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
  1327. // check for getStackTrace permission
  1328. SecurityManager security = System.getSecurityManager();
  1329. if (security != null) {
  1330. security.checkPermission(
  1331. SecurityConstants.GET_STACK_TRACE_PERMISSION);
  1332. security.checkPermission(
  1333. SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
  1334. }
  1335. // Get a snapshot of the list of all threads
  1336. Thread[] threads = getThreads();
  1337. StackTraceElement[][] traces = dumpThreads(threads);
  1338. Map<Thread, StackTraceElement[]> m
  1339. = new HashMap<Thread, StackTraceElement[]>(threads.length);
  1340. for (int i = 0; i < threads.length; i++) {
  1341. if (threads[i].isAlive()) {
  1342. StackTraceElement[] stackTrace = traces[i];
  1343. if (stackTrace == null) {
  1344. stackTrace = EMPTY_STACK_TRACE;
  1345. }
  1346. m.put(threads[i], stackTrace);
  1347. }
  1348. }
  1349. return m;
  1350. }
  1351. private static final RuntimePermission SUBCLASS_IMPLEMENTATION_PERMISSION =
  1352. new RuntimePermission("enableContextClassLoaderOverride");
  1353. /** cache of subclass security audit results */
  1354. private static final SoftCache subclassAudits = new SoftCache(10);
  1355. /**
  1356. * Verifies that this (possibly subclass) instance can be constructed
  1357. * without violating security constraints: the subclass must not override
  1358. * security-sensitive non-final methods, or else the
  1359. * "enableContextClassLoaderOverride" RuntimePermission is checked.
  1360. */
  1361. private static boolean isCCLOverridden(Class cl) {
  1362. if (cl == Thread.class)
  1363. return false;
  1364. Boolean result = null;
  1365. synchronized (subclassAudits) {
  1366. result = (Boolean) subclassAudits.get(cl);
  1367. if (result == null) {
  1368. /*
  1369. * Note: only new Boolean instances (i.e., not Boolean.TRUE or
  1370. * Boolean.FALSE) must be used as cache values, otherwise cache
  1371. * entry will pin associated class.
  1372. */
  1373. result = new Boolean(auditSubclass(cl));
  1374. subclassAudits.put(cl, result);
  1375. }
  1376. }
  1377. return result.booleanValue();
  1378. }
  1379. /**
  1380. * Performs reflective checks on given subclass to verify that it doesn't
  1381. * override security-sensitive non-final methods. Returns true if the
  1382. * subclass overrides any of the methods, false otherwise.
  1383. */
  1384. private static boolean auditSubclass(final Class subcl) {
  1385. Boolean result = (Boolean) AccessController.doPrivileged(
  1386. new PrivilegedAction() {
  1387. public Object run() {
  1388. for (Class cl = subcl;
  1389. cl != Thread.class;
  1390. cl = cl.getSuperclass())
  1391. {
  1392. try {
  1393. cl.getDeclaredMethod("getContextClassLoader", new Class[0]);
  1394. return Boolean.TRUE;
  1395. } catch (NoSuchMethodException ex) {
  1396. }
  1397. try {
  1398. Class[] params = {ClassLoader.class};
  1399. cl.getDeclaredMethod("setContextClassLoader", params);
  1400. return Boolean.TRUE;
  1401. } catch (NoSuchMethodException ex) {
  1402. }
  1403. }
  1404. return Boolean.FALSE;
  1405. }
  1406. }
  1407. );
  1408. return result.booleanValue();
  1409. }
  1410. private native static StackTraceElement[][] dumpThreads(Thread[] threads);
  1411. private native static Thread[] getThreads();
  1412. /**
  1413. * Returns the identifier of this Thread. The thread ID is a positive
  1414. * <tt>long</tt> number generated when this thread was created.
  1415. * The thread ID is unique and remains unchanged during its lifetime.
  1416. * When a thread is terminated, this thread ID may be reused.
  1417. *
  1418. * @return this thread's ID.
  1419. * @since 1.5
  1420. */
  1421. public long getId() {
  1422. return tid;
  1423. }
  1424. /**
  1425. * A thread state. A thread can be in one of the following states:
  1426. * <ul>
  1427. * <li>{@link #NEW}<br>
  1428. * A thread that has not yet started is in this state.
  1429. * </li>
  1430. * <li>{@link #RUNNABLE}<br>
  1431. * A thread executing in the Java virtual machine is in this state.
  1432. * </li>
  1433. * <li>{@link #BLOCKED}<br>
  1434. * A thread that is blocked waiting for a monitor lock
  1435. * is in this state.
  1436. * </li>
  1437. * <li>{@link #WAITING}<br>
  1438. * A thread that is waiting indefinitely for another thread to
  1439. * perform a particular action is in this state.
  1440. * </li>
  1441. * <li>{@link #TIMED_WAITING}<br>
  1442. * A thread that is waiting for another thread to perform an action
  1443. * for up to a specified waiting time is in this state.
  1444. * </li>
  1445. * <li>{@link #TERMINATED}<br>
  1446. * A thread that has exited is in this state.
  1447. * </li>
  1448. * </ul>
  1449. *
  1450. * <p>
  1451. * A thread can be in only one state at a given point in time.
  1452. * These states are virtual machine states which do not reflect
  1453. * any operating system thread states.
  1454. *
  1455. * @since 1.5
  1456. * @see Thread#getState
  1457. */
  1458. public enum State {
  1459. /**
  1460. * Thread state for a thread which has not yet started.
  1461. */
  1462. NEW,
  1463. /**
  1464. * Thread state for a runnable thread. A thread in the runnable
  1465. * state is executing in the Java virtual machine but it may
  1466. * be waiting for other resources from the operating system
  1467. * such as processor.
  1468. */
  1469. RUNNABLE,
  1470. /**
  1471. * Thread state for a thread blocked waiting for a monitor lock.
  1472. * A thread in the blocked state is waiting for a monitor lock
  1473. * to enter a synchronized block/method or
  1474. * reenter a synchronized block/method after calling
  1475. * {@link Object#wait() Object.wait}.
  1476. */
  1477. BLOCKED,
  1478. /**
  1479. * Thread state for a waiting thread.
  1480. * A thread is in the waiting state due to calling one of the
  1481. * following methods:
  1482. * <ul>
  1483. * <li>{@link Object#wait() Object.wait} with no timeout</li>
  1484. * <li>{@link Thread#join() Thread.join} with no timeout</li>
  1485. * <li>{@link LockSupport#park() LockSupport.park}</li>
  1486. * </ul>
  1487. *
  1488. * <p>A thread in the waiting state is waiting for another thread to
  1489. * perform a particular action.
  1490. *
  1491. * For example, a thread that has called <tt>Object.wait()</tt>
  1492. * on an object is waiting for another thread to call
  1493. * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
  1494. * that object. A thread that has called <tt>Thread.join()</tt>
  1495. * is waiting for a specified thread to terminate.
  1496. */
  1497. WAITING,
  1498. /**
  1499. * Thread state for a waiting thread with a specified waiting time.
  1500. * A thread is in the timed waiting state due to calling one of
  1501. * the following methods with a specified positive waiting time:
  1502. * <ul>
  1503. * <li>{@link Thread#sleep Thread.sleep}</li>
  1504. * <li>{@link Object#wait(long) Object.wait} with timeout</li>
  1505. * <li>{@link Thread#join(long) Thread.join} with timeout</li>
  1506. * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
  1507. * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
  1508. * </ul>
  1509. */
  1510. TIMED_WAITING,
  1511. /**
  1512. * Thread state for a terminated thread.
  1513. * The thread has completed execution.
  1514. */
  1515. TERMINATED;
  1516. }
  1517. /**
  1518. * Returns the state of this thread.
  1519. * This method is designed for use in monitoring of the system state,
  1520. * not for synchronization control.
  1521. *
  1522. * @return this thread's state.
  1523. * @since 1.5
  1524. */
  1525. public State getState() {
  1526. // get current thread state
  1527. return sun.misc.VM.toThreadState(threadStatus);
  1528. }
  1529. // Added in JSR-166
  1530. /**
  1531. * Interface for handlers invoked when a <tt>Thread</tt> abruptly
  1532. * terminates due to an uncaught exception.
  1533. * <p>When a thread is about to terminate due to an uncaught exception
  1534. * the Java Virtual Machine will query the thread for its
  1535. * <tt>UncaughtExceptionHandler</tt> using
  1536. * {@link Thread#getUncaughtExceptionHandler} and will invoke the handler's
  1537. * <tt>uncaughtException</tt> method, passing the thread and the
  1538. * exception as arguments.
  1539. * If a thread has not had its <tt>UncaughtExceptionHandler</tt>
  1540. * explicitly set, then its <tt>ThreadGroup</tt> object acts as its
  1541. * <tt>UncaughtExceptionHandler</tt>. If the <tt>ThreadGroup</tt> object
  1542. * has no
  1543. * special requirements for dealing with the exception, it can forward
  1544. * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
  1545. * default uncaught exception handler}.
  1546. *
  1547. * @see #setDefaultUncaughtExceptionHandler
  1548. * @see #setUncaughtExceptionHandler
  1549. * @see ThreadGroup#uncaughtException
  1550. * @since 1.5
  1551. */
  1552. public interface UncaughtExceptionHandler {
  1553. /**
  1554. * Method invoked when the given thread terminates due to the
  1555. * given uncaught exception.
  1556. * <p>Any exception thrown by this method will be ignored by the
  1557. * Java Virtual Machine.
  1558. * @param t the thread
  1559. * @param e the exception
  1560. */
  1561. void uncaughtException(Thread t, Throwable e);
  1562. }
  1563. // null unless explicitly set
  1564. private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
  1565. // null unless explicitly set
  1566. private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
  1567. /**
  1568. * Set the default handler invoked when a thread abruptly terminates
  1569. * due to an uncaught exception, and no other handler has been defined
  1570. * for that thread.
  1571. *
  1572. * <p>Uncaught exception handling is controlled first by the thread, then
  1573. * by the thread's {@link ThreadGroup} object and finally by the default
  1574. * uncaught exception handler. If the thread does not have an explicit
  1575. * uncaught exception handler set, and the thread's thread group
  1576. * (including parent thread groups) does not specialize its
  1577. * <tt>uncaughtException</tt> method, then the default handler's
  1578. * <tt>uncaughtException</tt> method will be invoked.
  1579. * <p>By setting the default uncaught exception handler, an application
  1580. * can change the way in which uncaught exceptions are handled (such as
  1581. * logging to a specific device, or file) for those threads that would
  1582. * already accept whatever "default" behavior the system
  1583. * provided.
  1584. *
  1585. * <p>Note that the default uncaught exception handler should not usually
  1586. * defer to the thread's <tt>ThreadGroup</tt> object, as that could cause
  1587. * infinite recursion.
  1588. *
  1589. * @param eh the object to use as the default uncaught exception handler.
  1590. * If <tt>null</tt> then there is no default handler.
  1591. *
  1592. * @throws SecurityException if a security manager is present and it
  1593. * denies <tt>{@link RuntimePermission}
  1594. * ("setDefaultUncaughtExceptionHandler")</tt>
  1595. *
  1596. * @see #setUncaughtExceptionHandler
  1597. * @see #getUncaughtExceptionHandler
  1598. * @see ThreadGroup#uncaughtException
  1599. * @since 1.5
  1600. */
  1601. public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
  1602. SecurityManager sm = System.getSecurityManager();
  1603. if (sm != null) {
  1604. sm.checkPermission(
  1605. new RuntimePermission("setDefaultUncaughtExceptionHandler")
  1606. );
  1607. }
  1608. defaultUncaughtExceptionHandler = eh;
  1609. }
  1610. /**
  1611. * Returns the default handler invoked when a thread abruptly terminates
  1612. * due to an uncaught exception. If the returned value is <tt>null</tt>,
  1613. * there is no default.
  1614. * @since 1.5
  1615. * @see #setDefaultUncaughtExceptionHandler
  1616. */
  1617. public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
  1618. return defaultUncaughtExceptionHandler;
  1619. }
  1620. /**
  1621. * Returns the handler invoked when this thread abruptly terminates
  1622. * due to an uncaught exception. If this thread has not had an
  1623. * uncaught exception handler explicitly set then this thread's
  1624. * <tt>ThreadGroup</tt> object is returned, unless this thread
  1625. * has terminated, in which case <tt>null</tt> is returned.
  1626. * @since 1.5
  1627. */
  1628. public UncaughtExceptionHandler getUncaughtExceptionHandler() {
  1629. return uncaughtExceptionHandler != null ?
  1630. uncaughtExceptionHandler : group;
  1631. }
  1632. /**
  1633. * Set the handler invoked when this thread abruptly terminates
  1634. * due to an uncaught exception.
  1635. * <p>A thread can take full control of how it responds to uncaught
  1636. * exceptions by having its uncaught exception handler explicitly set.
  1637. * If no such handler is set then the thread's <tt>ThreadGroup</tt>
  1638. * object acts as its handler.
  1639. * @param eh the object to use as this thread's uncaught exception
  1640. * handler. If <tt>null</tt> then this thread has no explicit handler.
  1641. * @throws SecurityException if the current thread is not allowed to
  1642. * modify this thread.
  1643. * @see #setDefaultUncaughtExceptionHandler
  1644. * @see ThreadGroup#uncaughtException
  1645. * @since 1.5
  1646. */
  1647. public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
  1648. checkAccess();
  1649. uncaughtExceptionHandler = eh;
  1650. }
  1651. /**
  1652. * Dispatch an uncaught exception to the handler. This method is
  1653. * intended to be called only by the JVM.
  1654. */
  1655. private void dispatchUncaughtException(Throwable e) {
  1656. getUncaughtExceptionHandler().uncaughtException(this, e);
  1657. }
  1658. /* Some private helper methods */
  1659. private native void setPriority0(int newPriority);
  1660. private native void stop0(Object o);
  1661. private native void suspend0();
  1662. private native void resume0();
  1663. private native void interrupt0();
  1664. }