Thread

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

ThreadLocal

  1. public class ThreadLocal<T> {
  2. /**
  3. * ThreadLocals rely on per-thread linear-probe hash maps attached
  4. * to each thread (Thread.threadLocals and
  5. * inheritableThreadLocals). The ThreadLocal objects act as keys,
  6. * searched via threadLocalHashCode. This is a custom hash code
  7. * (useful only within ThreadLocalMaps) that eliminates collisions
  8. * in the common case where consecutively constructed ThreadLocals
  9. * are used by the same threads, while remaining well-behaved in
  10. * less common cases.
  11. */
  12. private final int threadLocalHashCode = nextHashCode();
  13. /**
  14. * The next hash code to be given out. Updated atomically. Starts at
  15. * zero.
  16. */
  17. private static AtomicInteger nextHashCode =
  18. new AtomicInteger();
  19. /**
  20. * The difference between successively generated hash codes - turns
  21. * implicit sequential thread-local IDs into near-optimally spread
  22. * multiplicative hash values for power-of-two-sized tables.
  23. */
  24. private static final int HASH_INCREMENT = 0x61c88647;
  25. /**
  26. * Returns the next hash code.
  27. */
  28. private static int nextHashCode() {
  29. return nextHashCode.getAndAdd(HASH_INCREMENT);
  30. }
  31. /**
  32. * Returns the current thread's "initial value" for this
  33. * thread-local variable. This method will be invoked the first
  34. * time a thread accesses the variable with the {@link #get}
  35. * method, unless the thread previously invoked the {@link #set}
  36. * method, in which case the {@code initialValue} method will not
  37. * be invoked for the thread. Normally, this method is invoked at
  38. * most once per thread, but it may be invoked again in case of
  39. * subsequent invocations of {@link #remove} followed by {@link #get}.
  40. *
  41. * <p>This implementation simply returns {@code null}; if the
  42. * programmer desires thread-local variables to have an initial
  43. * value other than {@code null}, {@code ThreadLocal} must be
  44. * subclassed, and this method overridden. Typically, an
  45. * anonymous inner class will be used.
  46. *
  47. * @return the initial value for this thread-local
  48. */
  49. protected T initialValue() {
  50. return null;
  51. }
  52. /**
  53. * Creates a thread local variable. The initial value of the variable is
  54. * determined by invoking the {@code get} method on the {@code Supplier}.
  55. *
  56. * @param <S> the type of the thread local's value
  57. * @param supplier the supplier to be used to determine the initial value
  58. * @return a new thread local variable
  59. * @throws NullPointerException if the specified supplier is null
  60. * @since 1.8
  61. */
  62. public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
  63. return new SuppliedThreadLocal<>(supplier);
  64. }
  65. /**
  66. * Creates a thread local variable.
  67. * @see #withInitial(java.util.function.Supplier)
  68. */
  69. public ThreadLocal() {
  70. }
  71. /**
  72. * Returns the value in the current thread's copy of this
  73. * thread-local variable. If the variable has no value for the
  74. * current thread, it is first initialized to the value returned
  75. * by an invocation of the {@link #initialValue} method.
  76. *
  77. * @return the current thread's value of this thread-local
  78. */
  79. public T get() {
  80. Thread t = Thread.currentThread();
  81. ThreadLocalMap map = getMap(t);
  82. if (map != null) {
  83. ThreadLocalMap.Entry e = map.getEntry(this);
  84. if (e != null) {
  85. @SuppressWarnings("unchecked")
  86. T result = (T)e.value;
  87. return result;
  88. }
  89. }
  90. return setInitialValue();
  91. }
  92. /**
  93. * Variant of set() to establish initialValue. Used instead
  94. * of set() in case user has overridden the set() method.
  95. *
  96. * @return the initial value
  97. */
  98. private T setInitialValue() {
  99. T value = initialValue();
  100. Thread t = Thread.currentThread();
  101. ThreadLocalMap map = getMap(t);
  102. if (map != null)
  103. map.set(this, value);
  104. else
  105. createMap(t, value);
  106. return value;
  107. }
  108. /**
  109. * Sets the current thread's copy of this thread-local variable
  110. * to the specified value. Most subclasses will have no need to
  111. * override this method, relying solely on the {@link #initialValue}
  112. * method to set the values of thread-locals.
  113. *
  114. * @param value the value to be stored in the current thread's copy of
  115. * this thread-local.
  116. */
  117. public void set(T value) {
  118. Thread t = Thread.currentThread();
  119. ThreadLocalMap map = getMap(t);
  120. if (map != null)
  121. map.set(this, value);
  122. else
  123. createMap(t, value);
  124. }
  125. /**
  126. * Removes the current thread's value for this thread-local
  127. * variable. If this thread-local variable is subsequently
  128. * {@linkplain #get read} by the current thread, its value will be
  129. * reinitialized by invoking its {@link #initialValue} method,
  130. * unless its value is {@linkplain #set set} by the current thread
  131. * in the interim. This may result in multiple invocations of the
  132. * {@code initialValue} method in the current thread.
  133. *
  134. * @since 1.5
  135. */
  136. public void remove() {
  137. ThreadLocalMap m = getMap(Thread.currentThread());
  138. if (m != null)
  139. m.remove(this);
  140. }
  141. /**
  142. * Get the map associated with a ThreadLocal. Overridden in
  143. * InheritableThreadLocal.
  144. *
  145. * @param t the current thread
  146. * @return the map
  147. */
  148. ThreadLocalMap getMap(Thread t) {
  149. return t.threadLocals;
  150. }
  151. /**
  152. * Create the map associated with a ThreadLocal. Overridden in
  153. * InheritableThreadLocal.
  154. *
  155. * @param t the current thread
  156. * @param firstValue value for the initial entry of the map
  157. */
  158. void createMap(Thread t, T firstValue) {
  159. t.threadLocals = new ThreadLocalMap(this, firstValue);
  160. }
  161. /**
  162. * Factory method to create map of inherited thread locals.
  163. * Designed to be called only from Thread constructor.
  164. *
  165. * @param parentMap the map associated with parent thread
  166. * @return a map containing the parent's inheritable bindings
  167. */
  168. static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
  169. return new ThreadLocalMap(parentMap);
  170. }
  171. /**
  172. * Method childValue is visibly defined in subclass
  173. * InheritableThreadLocal, but is internally defined here for the
  174. * sake of providing createInheritedMap factory method without
  175. * needing to subclass the map class in InheritableThreadLocal.
  176. * This technique is preferable to the alternative of embedding
  177. * instanceof tests in methods.
  178. */
  179. T childValue(T parentValue) {
  180. throw new UnsupportedOperationException();
  181. }
  182. /**
  183. * An extension of ThreadLocal that obtains its initial value from
  184. * the specified {@code Supplier}.
  185. */
  186. static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {
  187. private final Supplier<? extends T> supplier;
  188. SuppliedThreadLocal(Supplier<? extends T> supplier) {
  189. this.supplier = Objects.requireNonNull(supplier);
  190. }
  191. @Override
  192. protected T initialValue() {
  193. return supplier.get();
  194. }
  195. }
  196. /**
  197. * ThreadLocalMap is a customized hash map suitable only for
  198. * maintaining thread local values. No operations are exported
  199. * outside of the ThreadLocal class. The class is package private to
  200. * allow declaration of fields in class Thread. To help deal with
  201. * very large and long-lived usages, the hash table entries use
  202. * WeakReferences for keys. However, since reference queues are not
  203. * used, stale entries are guaranteed to be removed only when
  204. * the table starts running out of space.
  205. */
  206. static class ThreadLocalMap {
  207. /**
  208. * The entries in this hash map extend WeakReference, using
  209. * its main ref field as the key (which is always a
  210. * ThreadLocal object). Note that null keys (i.e. entry.get()
  211. * == null) mean that the key is no longer referenced, so the
  212. * entry can be expunged from table. Such entries are referred to
  213. * as "stale entries" in the code that follows.
  214. */
  215. static class Entry extends WeakReference<ThreadLocal<?>> {
  216. /** The value associated with this ThreadLocal. */
  217. Object value;
  218. Entry(ThreadLocal<?> k, Object v) {
  219. super(k);
  220. value = v;
  221. }
  222. }
  223. /**
  224. * The initial capacity -- MUST be a power of two.
  225. */
  226. private static final int INITIAL_CAPACITY = 16;
  227. /**
  228. * The table, resized as necessary.
  229. * table.length MUST always be a power of two.
  230. */
  231. private Entry[] table;
  232. /**
  233. * The number of entries in the table.
  234. */
  235. private int size = 0;
  236. /**
  237. * The next size value at which to resize.
  238. */
  239. private int threshold; // Default to 0
  240. /**
  241. * Set the resize threshold to maintain at worst a 2/3 load factor.
  242. */
  243. private void setThreshold(int len) {
  244. threshold = len * 2 / 3;
  245. }
  246. /**
  247. * Increment i modulo len.
  248. */
  249. private static int nextIndex(int i, int len) {
  250. return ((i + 1 < len) ? i + 1 : 0);
  251. }
  252. /**
  253. * Decrement i modulo len.
  254. */
  255. private static int prevIndex(int i, int len) {
  256. return ((i - 1 >= 0) ? i - 1 : len - 1);
  257. }
  258. /**
  259. * Construct a new map initially containing (firstKey, firstValue).
  260. * ThreadLocalMaps are constructed lazily, so we only create
  261. * one when we have at least one entry to put in it.
  262. */
  263. ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
  264. table = new Entry[INITIAL_CAPACITY];
  265. int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
  266. table[i] = new Entry(firstKey, firstValue);
  267. size = 1;
  268. setThreshold(INITIAL_CAPACITY);
  269. }
  270. /**
  271. * Construct a new map including all Inheritable ThreadLocals
  272. * from given parent map. Called only by createInheritedMap.
  273. *
  274. * @param parentMap the map associated with parent thread.
  275. */
  276. private ThreadLocalMap(ThreadLocalMap parentMap) {
  277. Entry[] parentTable = parentMap.table;
  278. int len = parentTable.length;
  279. setThreshold(len);
  280. table = new Entry[len];
  281. for (int j = 0; j < len; j++) {
  282. Entry e = parentTable[j];
  283. if (e != null) {
  284. @SuppressWarnings("unchecked")
  285. ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
  286. if (key != null) {
  287. Object value = key.childValue(e.value);
  288. Entry c = new Entry(key, value);
  289. int h = key.threadLocalHashCode & (len - 1);
  290. while (table[h] != null)
  291. h = nextIndex(h, len);
  292. table[h] = c;
  293. size++;
  294. }
  295. }
  296. }
  297. }
  298. /**
  299. * Get the entry associated with key. This method
  300. * itself handles only the fast path: a direct hit of existing
  301. * key. It otherwise relays to getEntryAfterMiss. This is
  302. * designed to maximize performance for direct hits, in part
  303. * by making this method readily inlinable.
  304. *
  305. * @param key the thread local object
  306. * @return the entry associated with key, or null if no such
  307. */
  308. private Entry getEntry(ThreadLocal<?> key) {
  309. int i = key.threadLocalHashCode & (table.length - 1);
  310. Entry e = table[i];
  311. if (e != null && e.get() == key)
  312. return e;
  313. else
  314. return getEntryAfterMiss(key, i, e);
  315. }
  316. /**
  317. * Version of getEntry method for use when key is not found in
  318. * its direct hash slot.
  319. *
  320. * @param key the thread local object
  321. * @param i the table index for key's hash code
  322. * @param e the entry at table[i]
  323. * @return the entry associated with key, or null if no such
  324. */
  325. private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
  326. Entry[] tab = table;
  327. int len = tab.length;
  328. while (e != null) {
  329. ThreadLocal<?> k = e.get();
  330. if (k == key)
  331. return e;
  332. if (k == null)
  333. expungeStaleEntry(i);
  334. else
  335. i = nextIndex(i, len);
  336. e = tab[i];
  337. }
  338. return null;
  339. }
  340. /**
  341. * Set the value associated with key.
  342. *
  343. * @param key the thread local object
  344. * @param value the value to be set
  345. */
  346. private void set(ThreadLocal<?> key, Object value) {
  347. // We don't use a fast path as with get() because it is at
  348. // least as common to use set() to create new entries as
  349. // it is to replace existing ones, in which case, a fast
  350. // path would fail more often than not.
  351. Entry[] tab = table;
  352. int len = tab.length;
  353. int i = key.threadLocalHashCode & (len-1);
  354. for (Entry e = tab[i];
  355. e != null;
  356. e = tab[i = nextIndex(i, len)]) {
  357. ThreadLocal<?> k = e.get();
  358. if (k == key) {
  359. e.value = value;
  360. return;
  361. }
  362. if (k == null) {
  363. replaceStaleEntry(key, value, i);
  364. return;
  365. }
  366. }
  367. tab[i] = new Entry(key, value);
  368. int sz = ++size;
  369. if (!cleanSomeSlots(i, sz) && sz >= threshold)
  370. rehash();
  371. }
  372. /**
  373. * Remove the entry for key.
  374. */
  375. private void remove(ThreadLocal<?> key) {
  376. Entry[] tab = table;
  377. int len = tab.length;
  378. int i = key.threadLocalHashCode & (len-1);
  379. for (Entry e = tab[i];
  380. e != null;
  381. e = tab[i = nextIndex(i, len)]) {
  382. if (e.get() == key) {
  383. e.clear();
  384. expungeStaleEntry(i);
  385. return;
  386. }
  387. }
  388. }
  389. /**
  390. * Replace a stale entry encountered during a set operation
  391. * with an entry for the specified key. The value passed in
  392. * the value parameter is stored in the entry, whether or not
  393. * an entry already exists for the specified key.
  394. *
  395. * As a side effect, this method expunges all stale entries in the
  396. * "run" containing the stale entry. (A run is a sequence of entries
  397. * between two null slots.)
  398. *
  399. * @param key the key
  400. * @param value the value to be associated with key
  401. * @param staleSlot index of the first stale entry encountered while
  402. * searching for key.
  403. */
  404. private void replaceStaleEntry(ThreadLocal<?> key, Object value,
  405. int staleSlot) {
  406. Entry[] tab = table;
  407. int len = tab.length;
  408. Entry e;
  409. // Back up to check for prior stale entry in current run.
  410. // We clean out whole runs at a time to avoid continual
  411. // incremental rehashing due to garbage collector freeing
  412. // up refs in bunches (i.e., whenever the collector runs).
  413. int slotToExpunge = staleSlot;
  414. for (int i = prevIndex(staleSlot, len);
  415. (e = tab[i]) != null;
  416. i = prevIndex(i, len))
  417. if (e.get() == null)
  418. slotToExpunge = i;
  419. // Find either the key or trailing null slot of run, whichever
  420. // occurs first
  421. for (int i = nextIndex(staleSlot, len);
  422. (e = tab[i]) != null;
  423. i = nextIndex(i, len)) {
  424. ThreadLocal<?> k = e.get();
  425. // If we find key, then we need to swap it
  426. // with the stale entry to maintain hash table order.
  427. // The newly stale slot, or any other stale slot
  428. // encountered above it, can then be sent to expungeStaleEntry
  429. // to remove or rehash all of the other entries in run.
  430. if (k == key) {
  431. e.value = value;
  432. tab[i] = tab[staleSlot];
  433. tab[staleSlot] = e;
  434. // Start expunge at preceding stale entry if it exists
  435. if (slotToExpunge == staleSlot)
  436. slotToExpunge = i;
  437. cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
  438. return;
  439. }
  440. // If we didn't find stale entry on backward scan, the
  441. // first stale entry seen while scanning for key is the
  442. // first still present in the run.
  443. if (k == null && slotToExpunge == staleSlot)
  444. slotToExpunge = i;
  445. }
  446. // If key not found, put new entry in stale slot
  447. tab[staleSlot].value = null;
  448. tab[staleSlot] = new Entry(key, value);
  449. // If there are any other stale entries in run, expunge them
  450. if (slotToExpunge != staleSlot)
  451. cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
  452. }
  453. /**
  454. * Expunge a stale entry by rehashing any possibly colliding entries
  455. * lying between staleSlot and the next null slot. This also expunges
  456. * any other stale entries encountered before the trailing null. See
  457. * Knuth, Section 6.4
  458. *
  459. * @param staleSlot index of slot known to have null key
  460. * @return the index of the next null slot after staleSlot
  461. * (all between staleSlot and this slot will have been checked
  462. * for expunging).
  463. */
  464. private int expungeStaleEntry(int staleSlot) {
  465. Entry[] tab = table;
  466. int len = tab.length;
  467. // expunge entry at staleSlot
  468. tab[staleSlot].value = null;
  469. tab[staleSlot] = null;
  470. size--;
  471. // Rehash until we encounter null
  472. Entry e;
  473. int i;
  474. for (i = nextIndex(staleSlot, len);
  475. (e = tab[i]) != null;
  476. i = nextIndex(i, len)) {
  477. ThreadLocal<?> k = e.get();
  478. if (k == null) {
  479. e.value = null;
  480. tab[i] = null;
  481. size--;
  482. } else {
  483. int h = k.threadLocalHashCode & (len - 1);
  484. if (h != i) {
  485. tab[i] = null;
  486. // Unlike Knuth 6.4 Algorithm R, we must scan until
  487. // null because multiple entries could have been stale.
  488. while (tab[h] != null)
  489. h = nextIndex(h, len);
  490. tab[h] = e;
  491. }
  492. }
  493. }
  494. return i;
  495. }
  496. /**
  497. * Heuristically scan some cells looking for stale entries.
  498. * This is invoked when either a new element is added, or
  499. * another stale one has been expunged. It performs a
  500. * logarithmic number of scans, as a balance between no
  501. * scanning (fast but retains garbage) and a number of scans
  502. * proportional to number of elements, that would find all
  503. * garbage but would cause some insertions to take O(n) time.
  504. *
  505. * @param i a position known NOT to hold a stale entry. The
  506. * scan starts at the element after i.
  507. *
  508. * @param n scan control: {@code log2(n)} cells are scanned,
  509. * unless a stale entry is found, in which case
  510. * {@code log2(table.length)-1} additional cells are scanned.
  511. * When called from insertions, this parameter is the number
  512. * of elements, but when from replaceStaleEntry, it is the
  513. * table length. (Note: all this could be changed to be either
  514. * more or less aggressive by weighting n instead of just
  515. * using straight log n. But this version is simple, fast, and
  516. * seems to work well.)
  517. *
  518. * @return true if any stale entries have been removed.
  519. */
  520. private boolean cleanSomeSlots(int i, int n) {
  521. boolean removed = false;
  522. Entry[] tab = table;
  523. int len = tab.length;
  524. do {
  525. i = nextIndex(i, len);
  526. Entry e = tab[i];
  527. if (e != null && e.get() == null) {
  528. n = len;
  529. removed = true;
  530. i = expungeStaleEntry(i);
  531. }
  532. } while ( (n >>>= 1) != 0);
  533. return removed;
  534. }
  535. /**
  536. * Re-pack and/or re-size the table. First scan the entire
  537. * table removing stale entries. If this doesn't sufficiently
  538. * shrink the size of the table, double the table size.
  539. */
  540. private void rehash() {
  541. expungeStaleEntries();
  542. // Use lower threshold for doubling to avoid hysteresis
  543. if (size >= threshold - threshold / 4)
  544. resize();
  545. }
  546. /**
  547. * Double the capacity of the table.
  548. */
  549. private void resize() {
  550. Entry[] oldTab = table;
  551. int oldLen = oldTab.length;
  552. int newLen = oldLen * 2;
  553. Entry[] newTab = new Entry[newLen];
  554. int count = 0;
  555. for (int j = 0; j < oldLen; ++j) {
  556. Entry e = oldTab[j];
  557. if (e != null) {
  558. ThreadLocal<?> k = e.get();
  559. if (k == null) {
  560. e.value = null; // Help the GC
  561. } else {
  562. int h = k.threadLocalHashCode & (newLen - 1);
  563. while (newTab[h] != null)
  564. h = nextIndex(h, newLen);
  565. newTab[h] = e;
  566. count++;
  567. }
  568. }
  569. }
  570. setThreshold(newLen);
  571. size = count;
  572. table = newTab;
  573. }
  574. /**
  575. * Expunge all stale entries in the table.
  576. */
  577. private void expungeStaleEntries() {
  578. Entry[] tab = table;
  579. int len = tab.length;
  580. for (int j = 0; j < len; j++) {
  581. Entry e = tab[j];
  582. if (e != null && e.get() == null)
  583. expungeStaleEntry(j);
  584. }
  585. }
  586. }
  587. }