1. /*
  2. * @(#)Thread.java 1.127 03/01/23
  3. *
  4. * Copyright 2003 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.util.Map;
  11. import java.util.Collections;
  12. import sun.nio.ch.Interruptible;
  13. import sun.security.util.SecurityConstants;
  14. /**
  15. * A <i>thread</i> is a thread of execution in a program. The Java
  16. * Virtual Machine allows an application to have multiple threads of
  17. * execution running concurrently.
  18. * <p>
  19. * Every thread has a priority. Threads with higher priority are
  20. * executed in preference to threads with lower priority. Each thread
  21. * may or may not also be marked as a daemon. When code running in
  22. * some thread creates a new <code>Thread</code> object, the new
  23. * thread has its priority initially set equal to the priority of the
  24. * creating thread, and is a daemon thread if and only if the
  25. * creating thread is a daemon.
  26. * <p>
  27. * When a Java Virtual Machine starts up, there is usually a single
  28. * non-daemon thread (which typically calls the method named
  29. * <code>main</code> of some designated class). The Java Virtual
  30. * Machine continues to execute threads until either of the following
  31. * occurs:
  32. * <ul>
  33. * <li>The <code>exit</code> method of class <code>Runtime</code> has been
  34. * called and the security manager has permitted the exit operation
  35. * to take place.
  36. * <li>All threads that are not daemon threads have died, either by
  37. * returning from the call to the <code>run</code> method or by
  38. * throwing an exception that propagates beyond the <code>run</code>
  39. * method.
  40. * </ul>
  41. * <p>
  42. * There are two ways to create a new thread of execution. One is to
  43. * declare a class to be a subclass of <code>Thread</code>. This
  44. * subclass should override the <code>run</code> method of class
  45. * <code>Thread</code>. An instance of the subclass can then be
  46. * allocated and started. For example, a thread that computes primes
  47. * larger than a stated value could be written as follows:
  48. * <p><hr><blockquote><pre>
  49. * class PrimeThread extends Thread {
  50. * long minPrime;
  51. * PrimeThread(long minPrime) {
  52. * this.minPrime = minPrime;
  53. * }
  54. *
  55. * public void run() {
  56. * // compute primes larger than minPrime
  57. *  . . .
  58. * }
  59. * }
  60. * </pre></blockquote><hr>
  61. * <p>
  62. * The following code would then create a thread and start it running:
  63. * <p><blockquote><pre>
  64. * PrimeThread p = new PrimeThread(143);
  65. * p.start();
  66. * </pre></blockquote>
  67. * <p>
  68. * The other way to create a thread is to declare a class that
  69. * implements the <code>Runnable</code> interface. That class then
  70. * implements the <code>run</code> method. An instance of the class can
  71. * then be allocated, passed as an argument when creating
  72. * <code>Thread</code>, and started. The same example in this other
  73. * style looks like the following:
  74. * <p><hr><blockquote><pre>
  75. * class PrimeRun implements Runnable {
  76. * long minPrime;
  77. * PrimeRun(long minPrime) {
  78. * this.minPrime = minPrime;
  79. * }
  80. *
  81. * public void run() {
  82. * // compute primes larger than minPrime
  83. *  . . .
  84. * }
  85. * }
  86. * </pre></blockquote><hr>
  87. * <p>
  88. * The following code would then create a thread and start it running:
  89. * <p><blockquote><pre>
  90. * PrimeRun p = new PrimeRun(143);
  91. * new Thread(p).start();
  92. * </pre></blockquote>
  93. * <p>
  94. * Every thread has a name for identification purposes. More than
  95. * one thread may have the same name. If a name is not specified when
  96. * a thread is created, a new name is generated for it.
  97. *
  98. * @author unascribed
  99. * @version 1.127, 01/23/03
  100. * @see java.lang.Runnable
  101. * @see java.lang.Runtime#exit(int)
  102. * @see java.lang.Thread#run()
  103. * @see java.lang.Thread#stop()
  104. * @since JDK1.0
  105. */
  106. public
  107. class Thread implements Runnable {
  108. /* Make sure registerNatives is the first thing <clinit> does. */
  109. private static native void registerNatives();
  110. static {
  111. registerNatives();
  112. }
  113. private char name[];
  114. private int priority;
  115. private Thread threadQ;
  116. private long eetop;
  117. /* Whether or not to single_step this thread. */
  118. private boolean single_step;
  119. /* Whether or not the thread is a daemon thread. */
  120. private boolean daemon = false;
  121. /* Whether or not this thread was asked to exit before it runs.*/
  122. private boolean stillborn = false;
  123. /* What will be run. */
  124. private Runnable target;
  125. /* The group of this thread */
  126. private ThreadGroup group;
  127. /* The context ClassLoader for this thread */
  128. private ClassLoader contextClassLoader;
  129. /* The inherited AccessControlContext of this thread */
  130. private AccessControlContext inheritedAccessControlContext;
  131. /* For autonumbering anonymous threads. */
  132. private static int threadInitNumber;
  133. private static synchronized int nextThreadNum() {
  134. return threadInitNumber++;
  135. }
  136. /* ThreadLocal values pertaining to this thread. This map is maintained
  137. * by the ThreadLocal class. */
  138. ThreadLocal.ThreadLocalMap threadLocals = null;
  139. /*
  140. * InheritableThreadLocal values pertaining to this thread. This map is
  141. * maintained by the InheritableThreadLocal class.
  142. */
  143. ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
  144. /*
  145. * The requested stack size for this thread, or 0 if the creator did
  146. * not specify a stack size. It is up to the VM to do whatever it
  147. * likes with this number; some VMs will ignore it.
  148. */
  149. private long stackSize;
  150. /* The object in which this thread is blocked in an interruptible I/O
  151. * operation, if any. The blocker's interrupt method() should be invoked
  152. * before setting this thread's interrupt status.
  153. */
  154. private volatile Interruptible blocker;
  155. /* Set the blocker field; invoked via reflection magic from java.nio code
  156. */
  157. private void blockedOn(Interruptible b) {
  158. blocker = b;
  159. }
  160. /**
  161. * The minimum priority that a thread can have.
  162. */
  163. public final static int MIN_PRIORITY = 1;
  164. /**
  165. * The default priority that is assigned to a thread.
  166. */
  167. public final static int NORM_PRIORITY = 5;
  168. /**
  169. * The maximum priority that a thread can have.
  170. */
  171. public final static int MAX_PRIORITY = 10;
  172. /**
  173. * Returns a reference to the currently executing thread object.
  174. *
  175. * @return the currently executing thread.
  176. */
  177. public static native Thread currentThread();
  178. /**
  179. * Causes the currently executing thread object to temporarily pause
  180. * and allow other threads to execute.
  181. */
  182. public static native void yield();
  183. /**
  184. * Causes the currently executing thread to sleep (temporarily cease
  185. * execution) for the specified number of milliseconds. The thread
  186. * does not lose ownership of any monitors.
  187. *
  188. * @param millis the length of time to sleep in milliseconds.
  189. * @exception InterruptedException if another thread has interrupted
  190. * the current thread. The <i>interrupted status</i> of the
  191. * current thread is cleared when this exception is thrown.
  192. * @see java.lang.Object#notify()
  193. */
  194. public static native void sleep(long millis) throws InterruptedException;
  195. /**
  196. * Causes the currently executing thread to sleep (cease execution)
  197. * for the specified number of milliseconds plus the specified number
  198. * of nanoseconds. The thread does not lose ownership of any monitors.
  199. *
  200. * @param millis the length of time to sleep in milliseconds.
  201. * @param nanos 0-999999 additional nanoseconds to sleep.
  202. * @exception IllegalArgumentException if the value of millis is
  203. * negative or the value of nanos is not in the range
  204. * 0-999999.
  205. * @exception InterruptedException if another thread has interrupted
  206. * the current thread. The <i>interrupted status</i> of the
  207. * current thread is cleared when this exception is thrown.
  208. * @see java.lang.Object#notify()
  209. */
  210. public static void sleep(long millis, int nanos)
  211. throws InterruptedException {
  212. if (millis < 0) {
  213. throw new IllegalArgumentException("timeout value is negative");
  214. }
  215. if (nanos < 0 || nanos > 999999) {
  216. throw new IllegalArgumentException(
  217. "nanosecond timeout value out of range");
  218. }
  219. if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
  220. millis++;
  221. }
  222. sleep(millis);
  223. }
  224. /**
  225. * Initialize a Thread.
  226. *
  227. * @param g the Thread group
  228. * @param target the object whose run() method gets called
  229. * @param name the name of the new Thread
  230. * @param stackSize the desired stack size for the new thread, or
  231. * zero to indicate that this parameter is to be ignored.
  232. */
  233. private void init(ThreadGroup g, Runnable target, String name,
  234. long stackSize) {
  235. Thread parent = currentThread();
  236. if (g == null) {
  237. /* Determine if it's an applet or not */
  238. SecurityManager security = System.getSecurityManager();
  239. /* If there is a security manager, ask the security manager
  240. what to do. */
  241. if (security != null) {
  242. g = security.getThreadGroup();
  243. }
  244. /* If the security doesn't have a strong opinion of the matter
  245. use the parent thread group. */
  246. if (g == null) {
  247. g = parent.getThreadGroup();
  248. }
  249. }
  250. /* checkAccess regardless of whether or not threadgroup is
  251. explicitly passed in. */
  252. g.checkAccess();
  253. this.group = g;
  254. this.daemon = parent.isDaemon();
  255. this.priority = parent.getPriority();
  256. this.name = name.toCharArray();
  257. this.contextClassLoader = parent.contextClassLoader;
  258. this.inheritedAccessControlContext = AccessController.getContext();
  259. this.target = target;
  260. setPriority(priority);
  261. if (parent.inheritableThreadLocals != null)
  262. this.inheritableThreadLocals =
  263. ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
  264. /* Stash the specified stack size in case the VM cares */
  265. this.stackSize = stackSize;
  266. g.add(this);
  267. }
  268. /**
  269. * Allocates a new <code>Thread</code> object. This constructor has
  270. * the same effect as <code>Thread(null, null,</code>
  271. * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
  272. * a newly generated name. Automatically generated names are of the
  273. * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
  274. *
  275. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  276. * java.lang.Runnable, java.lang.String)
  277. */
  278. public Thread() {
  279. init(null, null, "Thread-" + nextThreadNum(), 0);
  280. }
  281. /**
  282. * Allocates a new <code>Thread</code> object. This constructor has
  283. * the same effect as <code>Thread(null, target,</code>
  284. * <i>gname</i><code>)</code>, where <i>gname</i> is
  285. * a newly generated name. Automatically generated names are of the
  286. * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
  287. *
  288. * @param target the object whose <code>run</code> method is called.
  289. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  290. * java.lang.Runnable, java.lang.String)
  291. */
  292. public Thread(Runnable target) {
  293. init(null, target, "Thread-" + nextThreadNum(), 0);
  294. }
  295. /**
  296. * Allocates a new <code>Thread</code> object. This constructor has
  297. * the same effect as <code>Thread(group, target,</code>
  298. * <i>gname</i><code>)</code>, where <i>gname</i> is
  299. * a newly generated name. Automatically generated names are of the
  300. * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
  301. *
  302. * @param group the thread group.
  303. * @param target the object whose <code>run</code> method is called.
  304. * @exception SecurityException if the current thread cannot create a
  305. * thread in the specified thread group.
  306. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  307. * java.lang.Runnable, java.lang.String)
  308. */
  309. public Thread(ThreadGroup group, Runnable target) {
  310. init(group, target, "Thread-" + nextThreadNum(), 0);
  311. }
  312. /**
  313. * Allocates a new <code>Thread</code> object. This constructor has
  314. * the same effect as <code>Thread(null, null, name)</code>.
  315. *
  316. * @param name the name of the new thread.
  317. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  318. * java.lang.Runnable, java.lang.String)
  319. */
  320. public Thread(String name) {
  321. init(null, null, name, 0);
  322. }
  323. /**
  324. * Allocates a new <code>Thread</code> object. This constructor has
  325. * the same effect as <code>Thread(group, null, name)</code>
  326. *
  327. * @param group the thread group.
  328. * @param name the name of the new thread.
  329. * @exception SecurityException if the current thread cannot create a
  330. * thread in the specified thread group.
  331. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  332. * java.lang.Runnable, java.lang.String)
  333. */
  334. public Thread(ThreadGroup group, String name) {
  335. init(group, null, name, 0);
  336. }
  337. /**
  338. * Allocates a new <code>Thread</code> object. This constructor has
  339. * the same effect as <code>Thread(null, target, name)</code>.
  340. *
  341. * @param target the object whose <code>run</code> method is called.
  342. * @param name the name of the new thread.
  343. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  344. * java.lang.Runnable, java.lang.String)
  345. */
  346. public Thread(Runnable target, String name) {
  347. init(null, target, name, 0);
  348. }
  349. /**
  350. * Allocates a new <code>Thread</code> object so that it has
  351. * <code>target</code> as its run object, has the specified
  352. * <code>name</code> as its name, and belongs to the thread group
  353. * referred to by <code>group</code>.
  354. * <p>
  355. * If <code>group</code> is <code>null</code> and there is a
  356. * security manager, the group is determined by the security manager's
  357. * <code>getThreadGroup</code> method. If <code>group</code> is
  358. * <code>null</code> and there is not a security manager, or the
  359. * security manager's <code>getThreadGroup</code> method returns
  360. * <code>null</code>, the group is set to be the same ThreadGroup
  361. * as the thread that is creating the new thread.
  362. *
  363. * <p>If there is a security manager, its <code>checkAccess</code>
  364. * method is called with the ThreadGroup as its argument.
  365. * This may result in a SecurityException.
  366. * <p>
  367. * If the <code>target</code> argument is not <code>null</code>, the
  368. * <code>run</code> method of the <code>target</code> is called when
  369. * this thread is started. If the target argument is
  370. * <code>null</code>, this thread's <code>run</code> method is called
  371. * when this thread is started.
  372. * <p>
  373. * The priority of the newly created thread is set equal to the
  374. * priority of the thread creating it, that is, the currently running
  375. * thread. The method <code>setPriority</code> may be used to
  376. * change the priority to a new value.
  377. * <p>
  378. * The newly created thread is initially marked as being a daemon
  379. * thread if and only if the thread creating it is currently marked
  380. * as a daemon thread. The method <code>setDaemon </code> may be used
  381. * to change whether or not a thread is a daemon.
  382. *
  383. * @param group the thread group.
  384. * @param target the object whose <code>run</code> method is called.
  385. * @param name the name of the new thread.
  386. * @exception SecurityException if the current thread cannot create a
  387. * thread in the specified thread group.
  388. * @see java.lang.Runnable#run()
  389. * @see java.lang.Thread#run()
  390. * @see java.lang.Thread#setDaemon(boolean)
  391. * @see java.lang.Thread#setPriority(int)
  392. * @see java.lang.ThreadGroup#checkAccess()
  393. * @see SecurityManager#checkAccess
  394. */
  395. public Thread(ThreadGroup group, Runnable target, String name) {
  396. init(group, target, name, 0);
  397. }
  398. /**
  399. * Allocates a new <code>Thread</code> object so that it has
  400. * <code>target</code> as its run object, has the specified
  401. * <code>name</code> as its name, belongs to the thread group referred to
  402. * by <code>group</code>, and has the specified <i>stack size</i>.
  403. *
  404. * <p>This constructor is identical to {@link
  405. * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact
  406. * that it allows the thread stack size to be specified. The stack size
  407. * is the approximate number of bytes of address space that the virtual
  408. * machine is to allocate for this thread's stack. <b>The effect of the
  409. * <tt>stackSize</tt> parameter, if any, is highly platform dependent.</b>
  410. *
  411. * <p>On some platforms, specifying a higher value for the
  412. * <tt>stackSize</tt> parameter may allow a thread to achieve greater
  413. * recursion depth before throwing a {@link StackOverflowError}.
  414. * Similarly, specifying a lower value may allow a greater number of
  415. * threads to exist concurrently without throwing an an {@link
  416. * OutOfMemoryError} (or other internal error). The details of
  417. * the relationship between the value of the <tt>stackSize</tt> parameter
  418. * and the maximum recursion depth and concurrency level are
  419. * platform-dependent. <b>On some platforms, the value of the
  420. * <tt>stackSize</tt> parameter may have no effect whatsoever.</b>
  421. *
  422. * <p>The virtual machine is free to treat the <tt>stackSize</tt>
  423. * parameter as a suggestion. If the specified value is unreasonably low
  424. * for the platform, the virtual machine may instead use some
  425. * platform-specific minimum value; if the specified value is unreasonably
  426. * high, the virtual machine may instead use some platform-specific
  427. * maximum. Likewise, the virtual machine is free to round the specified
  428. * value up or down as it sees fit (or to ignore it completely).
  429. *
  430. * <p>Specifying a value of zero for the <tt>stackSize</tt> parameter will
  431. * cause this constructor to behave exactly like the
  432. * <tt>Thread(ThreadGroup, Runnable, String)</tt> constructor.
  433. *
  434. * <p><i>Due to the platform-dependent nature of the behavior of this
  435. * constructor, extreme care should be exercised in its use.
  436. * The thread stack size necessary to perform a given computation will
  437. * likely vary from one JRE implementation to another. In light of this
  438. * variation, careful tuning of the stack size parameter may be required,
  439. * and the tuning may need to be repeated for each JRE implementation on
  440. * which an application is to run.</i>
  441. *
  442. * <p>Implementation note: Java platform implementers are encouraged to
  443. * document their implementation's behavior with respect to the
  444. * <tt>stackSize parameter</tt>.
  445. *
  446. * @param group the thread group.
  447. * @param target the object whose <code>run</code> method is called.
  448. * @param name the name of the new thread.
  449. * @param stackSize the desired stack size for the new thread, or
  450. * zero to indicate that this parameter is to be ignored.
  451. * @exception SecurityException if the current thread cannot create a
  452. * thread in the specified thread group.
  453. */
  454. public Thread(ThreadGroup group, Runnable target, String name,
  455. long stackSize) {
  456. init(group, target, name, stackSize);
  457. }
  458. /**
  459. * Causes this thread to begin execution; the Java Virtual Machine
  460. * calls the <code>run</code> method of this thread.
  461. * <p>
  462. * The result is that two threads are running concurrently: the
  463. * current thread (which returns from the call to the
  464. * <code>start</code> method) and the other thread (which executes its
  465. * <code>run</code> method).
  466. *
  467. * @exception IllegalThreadStateException if the thread was already
  468. * started.
  469. * @see java.lang.Thread#run()
  470. * @see java.lang.Thread#stop()
  471. */
  472. public synchronized native void start();
  473. /**
  474. * If this thread was constructed using a separate
  475. * <code>Runnable</code> run object, then that
  476. * <code>Runnable</code> object's <code>run</code> method is called;
  477. * otherwise, this method does nothing and returns.
  478. * <p>
  479. * Subclasses of <code>Thread</code> should override this method.
  480. *
  481. * @see java.lang.Thread#start()
  482. * @see java.lang.Thread#stop()
  483. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  484. * java.lang.Runnable, java.lang.String)
  485. * @see java.lang.Runnable#run()
  486. */
  487. public void run() {
  488. if (target != null) {
  489. target.run();
  490. }
  491. }
  492. /**
  493. * This method is called by the system to give a Thread
  494. * a chance to clean up before it actually exits.
  495. */
  496. private void exit() {
  497. if (group != null) {
  498. group.remove(this);
  499. group = null;
  500. }
  501. /* Aggressively null object connected to Thread: see bug 4006245 */
  502. target = null;
  503. }
  504. /**
  505. * Forces the thread to stop executing.
  506. * <p>
  507. * If there is a security manager installed, its <code>checkAccess</code>
  508. * method is called with <code>this</code>
  509. * as its argument. This may result in a
  510. * <code>SecurityException</code> being raised (in the current thread).
  511. * <p>
  512. * If this thread is different from the current thread (that is, the current
  513. * thread is trying to stop a thread other than itself), the
  514. * security manager's <code>checkPermission</code> method (with a
  515. * <code>RuntimePermission("stopThread")</code> argument) is called in
  516. * addition.
  517. * Again, this may result in throwing a
  518. * <code>SecurityException</code> (in the current thread).
  519. * <p>
  520. * The thread represented by this thread is forced to stop whatever
  521. * it is doing abnormally and to throw a newly created
  522. * <code>ThreadDeath</code> object as an exception.
  523. * <p>
  524. * It is permitted to stop a thread that has not yet been started.
  525. * If the thread is eventually started, it immediately terminates.
  526. * <p>
  527. * An application should not normally try to catch
  528. * <code>ThreadDeath</code> unless it must do some extraordinary
  529. * cleanup operation (note that the throwing of
  530. * <code>ThreadDeath</code> causes <code>finally</code> clauses of
  531. * <code>try</code> statements to be executed before the thread
  532. * officially dies). If a <code>catch</code> clause catches a
  533. * <code>ThreadDeath</code> object, it is important to rethrow the
  534. * object so that the thread actually dies.
  535. * <p>
  536. * The top-level error handler that reacts to otherwise uncaught
  537. * exceptions does not print out a message or otherwise notify the
  538. * application if the uncaught exception is an instance of
  539. * <code>ThreadDeath</code>.
  540. *
  541. * @exception SecurityException if the current thread cannot
  542. * modify this thread.
  543. * @see java.lang.Thread#interrupt()
  544. * @see java.lang.Thread#checkAccess()
  545. * @see java.lang.Thread#run()
  546. * @see java.lang.Thread#start()
  547. * @see java.lang.ThreadDeath
  548. * @see java.lang.ThreadGroup#uncaughtException(java.lang.Thread,
  549. * java.lang.Throwable)
  550. * @see SecurityManager#checkAccess(Thread)
  551. * @see SecurityManager#checkPermission
  552. * @deprecated This method is inherently unsafe. Stopping a thread with
  553. * Thread.stop causes it to unlock all of the monitors that it
  554. * has locked (as a natural consequence of the unchecked
  555. * <code>ThreadDeath</code> exception propagating up the stack). If
  556. * any of the objects previously protected by these monitors were in
  557. * an inconsistent state, the damaged objects become visible to
  558. * other threads, potentially resulting in arbitrary behavior. Many
  559. * uses of <code>stop</code> should be replaced by code that simply
  560. * modifies some variable to indicate that the target thread should
  561. * stop running. The target thread should check this variable
  562. * regularly, and return from its run method in an orderly fashion
  563. * if the variable indicates that it is to stop running. If the
  564. * target thread waits for long periods (on a condition variable,
  565. * for example), the <code>interrupt</code> method should be used to
  566. * interrupt the wait.
  567. * For more information, see
  568. * <a href="{@docRoot}/../guide/misc/threadPrimitiveDeprecation.html">Why
  569. * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  570. */
  571. public final void stop() {
  572. synchronized (this) {
  573. //if the thread is alreay dead, return
  574. if (!this.isAlive()) return;
  575. SecurityManager security = System.getSecurityManager();
  576. if (security != null) {
  577. checkAccess();
  578. if (this != Thread.currentThread()) {
  579. security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
  580. }
  581. }
  582. resume(); // Wake up thread if it was suspended; no-op otherwise
  583. stop0(new ThreadDeath());
  584. }
  585. }
  586. /**
  587. * Forces the thread to stop executing.
  588. * <p>
  589. * If there is a security manager installed, the <code>checkAccess</code>
  590. * method of this thread is called, which may result in a
  591. * <code>SecurityException</code> being raised (in the current thread).
  592. * <p>
  593. * If this thread is different from the current thread (that is, the current
  594. * thread is trying to stop a thread other than itself) or
  595. * <code>obj</code> is not an instance of <code>ThreadDeath</code>, the
  596. * security manager's <code>checkPermission</code> method (with the
  597. * <code>RuntimePermission("stopThread")</code> argument) is called in
  598. * addition.
  599. * Again, this may result in throwing a
  600. * <code>SecurityException</code> (in the current thread).
  601. * <p>
  602. * If the argument <code>obj</code> is null, a
  603. * <code>NullPointerException</code> is thrown (in the current thread).
  604. * <p>
  605. * The thread represented by this thread is forced to complete
  606. * whatever it is doing abnormally and to throw the
  607. * <code>Throwable</code> object <code>obj</code> as an exception. This
  608. * is an unusual action to take; normally, the <code>stop</code> method
  609. * that takes no arguments should be used.
  610. * <p>
  611. * It is permitted to stop a thread that has not yet been started.
  612. * If the thread is eventually started, it immediately terminates.
  613. *
  614. * @param obj the Throwable object to be thrown.
  615. * @exception SecurityException if the current thread cannot modify
  616. * this thread.
  617. * @see java.lang.Thread#interrupt()
  618. * @see java.lang.Thread#checkAccess()
  619. * @see java.lang.Thread#run()
  620. * @see java.lang.Thread#start()
  621. * @see java.lang.Thread#stop()
  622. * @see SecurityManager#checkAccess(Thread)
  623. * @see SecurityManager#checkPermission
  624. * @deprecated This method is inherently unsafe. See {@link #stop}
  625. * (with no arguments) for details. An additional danger of this
  626. * method is that it may be used to generate exceptions that the
  627. * target thread is unprepared to handle (including checked
  628. * exceptions that the thread could not possibly throw, were it
  629. * not for this method).
  630. * For more information, see
  631. * <a href="{@docRoot}/../guide/misc/threadPrimitiveDeprecation.html">Why
  632. * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  633. */
  634. public final synchronized void stop(Throwable obj) {
  635. SecurityManager security = System.getSecurityManager();
  636. if (security != null) {
  637. checkAccess();
  638. if ((this != Thread.currentThread()) ||
  639. (!(obj instanceof ThreadDeath))) {
  640. security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
  641. }
  642. }
  643. resume(); // Wake up thread if it was suspended; no-op otherwise
  644. stop0(obj);
  645. }
  646. /**
  647. * Interrupts this thread.
  648. *
  649. * <p> First the {@link #checkAccess() checkAccess} method of this thread
  650. * is invoked, which may cause a {@link SecurityException} to be thrown.
  651. *
  652. * <p> If this thread is blocked in an invocation of the {@link
  653. * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
  654. * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
  655. * class, or of the {@link #join()}, {@link #join(long)}, {@link
  656. * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
  657. * methods of this class, then its interrupt status will be cleared and it
  658. * will receive an {@link InterruptedException}.
  659. *
  660. * <p> If this thread is blocked in an I/O operation upon an {@link
  661. * java.nio.channels.InterruptibleChannel </code>interruptible
  662. * channel<code>} then the channel will be closed, the thread's interrupt
  663. * status will be set, and the thread will receive a {@link
  664. * java.nio.channels.ClosedByInterruptException}.
  665. *
  666. * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
  667. * then the thread's interrupt status will be set and it will return
  668. * immediately from the selection operation, possibly with a non-zero
  669. * value, just as if the selector's {@link
  670. * java.nio.channels.Selector#wakeup wakeup} method were invoked.
  671. *
  672. * <p> If none of the previous conditions hold then this thread's interrupt
  673. * status will be set. </p>
  674. *
  675. * @throws SecurityException
  676. * if the current thread cannot modify this thread
  677. *
  678. * @revised 1.4
  679. * @spec JSR-51
  680. */
  681. public void interrupt() {
  682. checkAccess();
  683. Interruptible b = blocker;
  684. if (b != null) {
  685. b.interrupt();
  686. }
  687. interrupt0();
  688. }
  689. /**
  690. * Tests whether the current thread has been interrupted. The
  691. * <i>interrupted status</i> of the thread is cleared by this method. In
  692. * other words, if this method were to be called twice in succession, the
  693. * second call would return false (unless the current thread were
  694. * interrupted again, after the first call had cleared its interrupted
  695. * status and before the second call had examined it).
  696. *
  697. * @return <code>true</code> if the current thread has been interrupted;
  698. * <code>false</code> otherwise.
  699. * @see java.lang.Thread#isInterrupted()
  700. */
  701. public static boolean interrupted() {
  702. return currentThread().isInterrupted(true);
  703. }
  704. /**
  705. * Tests whether this thread has been interrupted. The <i>interrupted
  706. * status</i> of the thread is unaffected by this method.
  707. *
  708. * @return <code>true</code> if this thread has been interrupted;
  709. * <code>false</code> otherwise.
  710. * @see java.lang.Thread#interrupted()
  711. */
  712. public boolean isInterrupted() {
  713. return isInterrupted(false);
  714. }
  715. /**
  716. * Tests if some Thread has been interrupted. The interrupted state
  717. * is reset or not based on the value of ClearInterrupted that is
  718. * passed.
  719. */
  720. private native boolean isInterrupted(boolean ClearInterrupted);
  721. /**
  722. * Destroys this thread, without any cleanup. Any monitors it has
  723. * locked remain locked. (This method is not implemented.)
  724. */
  725. public void destroy() {
  726. throw new NoSuchMethodError();
  727. }
  728. /**
  729. * Tests if this thread is alive. A thread is alive if it has
  730. * been started and has not yet died.
  731. *
  732. * @return <code>true</code> if this thread is alive;
  733. * <code>false</code> otherwise.
  734. */
  735. public final native boolean isAlive();
  736. /**
  737. * Suspends this thread.
  738. * <p>
  739. * First, the <code>checkAccess</code> method of this thread is called
  740. * with no arguments. This may result in throwing a
  741. * <code>SecurityException </code>(in the current thread).
  742. * <p>
  743. * If the thread is alive, it is suspended and makes no further
  744. * progress unless and until it is resumed.
  745. *
  746. * @exception SecurityException if the current thread cannot modify
  747. * this thread.
  748. * @see #checkAccess
  749. * @deprecated This method has been deprecated, as it is
  750. * inherently deadlock-prone. If the target thread holds a lock on the
  751. * monitor protecting a critical system resource when it is suspended, no
  752. * thread can access this resource until the target thread is resumed. If
  753. * the thread that would resume the target thread attempts to lock this
  754. * monitor prior to calling <code>resume</code>, deadlock results. Such
  755. * deadlocks typically manifest themselves as "frozen" processes.
  756. * For more information, see
  757. * <a href="{@docRoot}/../guide/misc/threadPrimitiveDeprecation.html">Why
  758. * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  759. */
  760. public final void suspend() {
  761. checkAccess();
  762. suspend0();
  763. }
  764. /**
  765. * Resumes a suspended thread.
  766. * <p>
  767. * First, the <code>checkAccess</code> method of this thread is called
  768. * with no arguments. This may result in throwing a
  769. * <code>SecurityException</code> (in the current thread).
  770. * <p>
  771. * If the thread is alive but suspended, it is resumed and is
  772. * permitted to make progress in its execution.
  773. *
  774. * @exception SecurityException if the current thread cannot modify this
  775. * thread.
  776. * @see #checkAccess
  777. * @see java.lang.Thread#suspend()
  778. * @deprecated This method exists solely for use with {@link #suspend},
  779. * which has been deprecated because it is deadlock-prone.
  780. * For more information, see
  781. * <a href="{@docRoot}/../guide/misc/threadPrimitiveDeprecation.html">Why
  782. * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  783. */
  784. public final void resume() {
  785. checkAccess();
  786. resume0();
  787. }
  788. /**
  789. * Changes the priority of this thread.
  790. * <p>
  791. * First the <code>checkAccess</code> method of this thread is called
  792. * with no arguments. This may result in throwing a
  793. * <code>SecurityException</code>.
  794. * <p>
  795. * Otherwise, the priority of this thread is set to the smaller of
  796. * the specified <code>newPriority</code> and the maximum permitted
  797. * priority of the thread's thread group.
  798. *
  799. * @param newPriority priority to set this thread to
  800. * @exception IllegalArgumentException If the priority is not in the
  801. * range <code>MIN_PRIORITY</code> to
  802. * <code>MAX_PRIORITY</code>.
  803. * @exception SecurityException if the current thread cannot modify
  804. * this thread.
  805. * @see #getPriority
  806. * @see java.lang.Thread#checkAccess()
  807. * @see java.lang.Thread#getPriority()
  808. * @see java.lang.Thread#getThreadGroup()
  809. * @see java.lang.Thread#MAX_PRIORITY
  810. * @see java.lang.Thread#MIN_PRIORITY
  811. * @see java.lang.ThreadGroup#getMaxPriority()
  812. */
  813. public final void setPriority(int newPriority) {
  814. checkAccess();
  815. if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
  816. throw new IllegalArgumentException();
  817. }
  818. if (newPriority > group.getMaxPriority()) {
  819. newPriority = group.getMaxPriority();
  820. }
  821. setPriority0(priority = newPriority);
  822. }
  823. /**
  824. * Returns this thread's priority.
  825. *
  826. * @return this thread's priority.
  827. * @see #setPriority
  828. * @see java.lang.Thread#setPriority(int)
  829. */
  830. public final int getPriority() {
  831. return priority;
  832. }
  833. /**
  834. * Changes the name of this thread to be equal to the argument
  835. * <code>name</code>.
  836. * <p>
  837. * First the <code>checkAccess</code> method of this thread is called
  838. * with no arguments. This may result in throwing a
  839. * <code>SecurityException</code>.
  840. *
  841. * @param name the new name for this thread.
  842. * @exception SecurityException if the current thread cannot modify this
  843. * thread.
  844. * @see #getName
  845. * @see java.lang.Thread#checkAccess()
  846. * @see java.lang.Thread#getName()
  847. */
  848. public final void setName(String name) {
  849. checkAccess();
  850. this.name = name.toCharArray();
  851. }
  852. /**
  853. * Returns this thread's name.
  854. *
  855. * @return this thread's name.
  856. * @see #setName
  857. * @see java.lang.Thread#setName(java.lang.String)
  858. */
  859. public final String getName() {
  860. return String.valueOf(name);
  861. }
  862. /**
  863. * Returns the thread group to which this thread belongs.
  864. * This method returns null if this thread has died
  865. * (been stopped).
  866. *
  867. * @return this thread's thread group.
  868. */
  869. public final ThreadGroup getThreadGroup() {
  870. return group;
  871. }
  872. /**
  873. * Returns the number of active threads in the current thread's thread
  874. * group.
  875. *
  876. * @return the number of active threads in the current thread's thread
  877. * group.
  878. */
  879. public static int activeCount() {
  880. return currentThread().getThreadGroup().activeCount();
  881. }
  882. /**
  883. * Copies into the specified array every active thread in
  884. * the current thread's thread group and its subgroups. This method simply
  885. * calls the <code>enumerate</code> method of the current thread's thread
  886. * group with the array argument.
  887. * <p>
  888. * First, if there is a security manager, that <code>enumerate</code>
  889. * method calls the security
  890. * manager's <code>checkAccess</code> method
  891. * with the thread group as its argument. This may result
  892. * in throwing a <code>SecurityException</code>.
  893. *
  894. * @param tarray an array of Thread objects to copy to
  895. * @return the number of threads put into the array
  896. * @exception SecurityException if a security manager exists and its
  897. * <code>checkAccess</code> method doesn't allow the operation.
  898. * @see java.lang.ThreadGroup#enumerate(java.lang.Thread[])
  899. * @see java.lang.SecurityManager#checkAccess(java.lang.ThreadGroup)
  900. */
  901. public static int enumerate(Thread tarray[]) {
  902. return currentThread().getThreadGroup().enumerate(tarray);
  903. }
  904. /**
  905. * Counts the number of stack frames in this thread. The thread must
  906. * be suspended.
  907. *
  908. * @return the number of stack frames in this thread.
  909. * @exception IllegalThreadStateException if this thread is not
  910. * suspended.
  911. * @deprecated The definition of this call depends on {@link #suspend},
  912. * which is deprecated. Further, the results of this call
  913. * were never well-defined.
  914. */
  915. public native int countStackFrames();
  916. /**
  917. * Waits at most <code>millis</code> milliseconds for this thread to
  918. * die. A timeout of <code>0</code> means to wait forever.
  919. *
  920. * @param millis the time to wait in milliseconds.
  921. * @exception InterruptedException if another thread has interrupted
  922. * the current thread. The <i>interrupted status</i> of the
  923. * current thread is cleared when this exception is thrown.
  924. */
  925. public final synchronized void join(long millis)
  926. throws InterruptedException {
  927. long base = System.currentTimeMillis();
  928. long now = 0;
  929. if (millis < 0) {
  930. throw new IllegalArgumentException("timeout value is negative");
  931. }
  932. if (millis == 0) {
  933. while (isAlive()) {
  934. wait(0);
  935. }
  936. } else {
  937. while (isAlive()) {
  938. long delay = millis - now;
  939. if (delay <= 0) {
  940. break;
  941. }
  942. wait(delay);
  943. now = System.currentTimeMillis() - base;
  944. }
  945. }
  946. }
  947. /**
  948. * Waits at most <code>millis</code> milliseconds plus
  949. * <code>nanos</code> nanoseconds for this thread to die.
  950. *
  951. * @param millis the time to wait in milliseconds.
  952. * @param nanos 0-999999 additional nanoseconds to wait.
  953. * @exception IllegalArgumentException if the value of millis is negative
  954. * the value of nanos is not in the range 0-999999.
  955. * @exception InterruptedException if another thread has interrupted
  956. * the current thread. The <i>interrupted status</i> of the
  957. * current thread is cleared when this exception is thrown.
  958. */
  959. public final synchronized void join(long millis, int nanos)
  960. throws InterruptedException {
  961. if (millis < 0) {
  962. throw new IllegalArgumentException("timeout value is negative");
  963. }
  964. if (nanos < 0 || nanos > 999999) {
  965. throw new IllegalArgumentException(
  966. "nanosecond timeout value out of range");
  967. }
  968. if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
  969. millis++;
  970. }
  971. join(millis);
  972. }
  973. /**
  974. * Waits for this thread to die.
  975. *
  976. * @exception InterruptedException if another thread has interrupted
  977. * the current thread. The <i>interrupted status</i> of the
  978. * current thread is cleared when this exception is thrown.
  979. */
  980. public final void join() throws InterruptedException {
  981. join(0);
  982. }
  983. /**
  984. * Prints a stack trace of the current thread. This method is used
  985. * only for debugging.
  986. *
  987. * @see java.lang.Throwable#printStackTrace()
  988. */
  989. public static void dumpStack() {
  990. new Exception("Stack trace").printStackTrace();
  991. }
  992. /**
  993. * Marks this thread as either a daemon thread or a user thread. The
  994. * Java Virtual Machine exits when the only threads running are all
  995. * daemon threads.
  996. * <p>
  997. * This method must be called before the thread is started.
  998. * <p>
  999. * This method first calls the <code>checkAccess</code> method
  1000. * of this thread
  1001. * with no arguments. This may result in throwing a
  1002. * <code>SecurityException </code>(in the current thread).
  1003. *
  1004. * @param on if <code>true</code>, marks this thread as a
  1005. * daemon thread.
  1006. * @exception IllegalThreadStateException if this thread is active.
  1007. * @exception SecurityException if the current thread cannot modify
  1008. * this thread.
  1009. * @see java.lang.Thread#isDaemon()
  1010. * @see #checkAccess
  1011. */
  1012. public final void setDaemon(boolean on) {
  1013. checkAccess();
  1014. if (isAlive()) {
  1015. throw new IllegalThreadStateException();
  1016. }
  1017. daemon = on;
  1018. }
  1019. /**
  1020. * Tests if this thread is a daemon thread.
  1021. *
  1022. * @return <code>true</code> if this thread is a daemon thread;
  1023. * <code>false</code> otherwise.
  1024. * @see java.lang.Thread#setDaemon(boolean)
  1025. */
  1026. public final boolean isDaemon() {
  1027. return daemon;
  1028. }
  1029. /**
  1030. * Determines if the currently running thread has permission to
  1031. * modify this thread.
  1032. * <p>
  1033. * If there is a security manager, its <code>checkAccess</code> method
  1034. * is called with this thread as its argument. This may result in
  1035. * throwing a <code>SecurityException</code>.
  1036. * <p>
  1037. * Note: This method was mistakenly non-final in JDK 1.1.
  1038. * It has been made final in the Java 2 Platform.
  1039. *
  1040. * @exception SecurityException if the current thread is not allowed to
  1041. * access this thread.
  1042. * @see java.lang.SecurityManager#checkAccess(java.lang.Thread)
  1043. */
  1044. public final void checkAccess() {
  1045. SecurityManager security = System.getSecurityManager();
  1046. if (security != null) {
  1047. security.checkAccess(this);
  1048. }
  1049. }
  1050. /**
  1051. * Returns a string representation of this thread, including the
  1052. * thread's name, priority, and thread group.
  1053. *
  1054. * @return a string representation of this thread.
  1055. */
  1056. public String toString() {
  1057. ThreadGroup group = getThreadGroup();
  1058. if (group != null) {
  1059. return "Thread[" + getName() + "," + getPriority() + "," +
  1060. group.getName() + "]";
  1061. } else {
  1062. return "Thread[" + getName() + "," + getPriority() + "," +
  1063. "" + "]";
  1064. }
  1065. }
  1066. /**
  1067. * Returns the context ClassLoader for this Thread. The context
  1068. * ClassLoader is provided by the creator of the thread for use
  1069. * by code running in this thread when loading classes and resources.
  1070. * If not set, the default is the ClassLoader context of the parent
  1071. * Thread. The context ClassLoader of the primordial thread is
  1072. * typically set to the class loader used to load the application.
  1073. *
  1074. * <p>First, if there is a security manager, and the caller's class
  1075. * loader is not null and the caller's class loader is not the same as or
  1076. * an ancestor of the context class loader for the thread whose
  1077. * context class loader is being requested, then the security manager's
  1078. * <code>checkPermission</code>
  1079. * method is called with a
  1080. * <code>RuntimePermission("getClassLoader")</code> permission
  1081. * to see if it's ok to get the context ClassLoader..
  1082. *
  1083. * @return the context ClassLoader for this Thread
  1084. *
  1085. * @throws SecurityException
  1086. * if a security manager exists and its
  1087. * <code>checkPermission</code> method doesn't allow
  1088. * getting the context ClassLoader.
  1089. * @see #setContextClassLoader
  1090. * @see SecurityManager#checkPermission
  1091. * @see java.lang.RuntimePermission
  1092. *
  1093. * @since 1.2
  1094. */
  1095. public ClassLoader getContextClassLoader() {
  1096. if (contextClassLoader == null)
  1097. return null;
  1098. SecurityManager sm = System.getSecurityManager();
  1099. if (sm != null) {
  1100. ClassLoader ccl = ClassLoader.getCallerClassLoader();
  1101. if (ccl != null && ccl != contextClassLoader &&
  1102. !contextClassLoader.isAncestor(ccl)) {
  1103. sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
  1104. }
  1105. }
  1106. return contextClassLoader;
  1107. }
  1108. /**
  1109. * Sets the context ClassLoader for this Thread. The context
  1110. * ClassLoader can be set when a thread is created, and allows
  1111. * the creator of the thread to provide the appropriate class loader
  1112. * to code running in the thread when loading classes and resources.
  1113. *
  1114. * <p>First, if there is a security manager, its <code>checkPermission</code>
  1115. * method is called with a
  1116. * <code>RuntimePermission("setContextClassLoader")</code> permission
  1117. * to see if it's ok to set the context ClassLoader..
  1118. *
  1119. * @param cl the context ClassLoader for this Thread
  1120. *
  1121. * @exception SecurityException if the current thread cannot set the
  1122. * context ClassLoader.
  1123. * @see #getContextClassLoader
  1124. * @see SecurityManager#checkPermission
  1125. * @see java.lang.RuntimePermission
  1126. *
  1127. * @since 1.2
  1128. */
  1129. public void setContextClassLoader(ClassLoader cl) {
  1130. SecurityManager sm = System.getSecurityManager();
  1131. if (sm != null) {
  1132. sm.checkPermission(new RuntimePermission("setContextClassLoader"));
  1133. }
  1134. contextClassLoader = cl;
  1135. }
  1136. /**
  1137. * Returns <tt>true</tt> if and only if the current thread holds the
  1138. * monitor lock on the specified object.
  1139. *
  1140. * <p>This method is designed to allow a program to assert that
  1141. * the current thread already holds a specified lock:
  1142. * <pre>
  1143. * assert Thread.holdsLock(obj);
  1144. * </pre>
  1145. *
  1146. * @param obj the object on which to test lock ownership
  1147. * @throws NullPointerException if obj is <tt>null</tt>
  1148. * @return <tt>true</tt> if the current thread holds the monitor lock on
  1149. * the specified object.
  1150. * @since 1.4
  1151. */
  1152. public static native boolean holdsLock(Object obj);
  1153. /* Some private helper methods */
  1154. private native void setPriority0(int newPriority);
  1155. private native void stop0(Object o);
  1156. private native void suspend0();
  1157. private native void resume0();
  1158. private native void interrupt0();
  1159. }