1. /*
  2. * @(#)Condition.java 1.5 04/07/12
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util.concurrent.locks;
  8. import java.util.concurrent.*;
  9. import java.util.Date;
  10. /**
  11. * <tt>Condition</tt> factors out the <tt>Object</tt> monitor
  12. * methods ({@link Object#wait() wait}, {@link Object#notify notify}
  13. * and {@link Object#notifyAll notifyAll}) into distinct objects to
  14. * give the effect of having multiple wait-sets per object, by
  15. * combining them with the use of arbitrary {@link Lock} implementations.
  16. * Where a <tt>Lock</tt> replaces the use of <tt>synchronized</tt> methods
  17. * and statements, a <tt>Condition</tt> replaces the use of the Object
  18. * monitor methods.
  19. *
  20. * <p>Conditions (also known as <em>condition queues</em> or
  21. * <em>condition variables</em>) provide a means for one thread to
  22. * suspend execution (to "wait") until notified by another
  23. * thread that some state condition may now be true. Because access
  24. * to this shared state information occurs in different threads, it
  25. * must be protected, so a lock of some form is associated with the
  26. * condition. The key property that waiting for a condition provides
  27. * is that it <em>atomically</em> releases the associated lock and
  28. * suspends the current thread, just like <tt>Object.wait</tt>.
  29. *
  30. * <p>A <tt>Condition</tt> instance is intrinsically bound to a lock.
  31. * To obtain a <tt>Condition</tt> instance for a particular {@link Lock}
  32. * instance use its {@link Lock#newCondition newCondition()} method.
  33. *
  34. * <p>As an example, suppose we have a bounded buffer which supports
  35. * <tt>put</tt> and <tt>take</tt> methods. If a
  36. * <tt>take</tt> is attempted on an empty buffer, then the thread will block
  37. * until an item becomes available; if a <tt>put</tt> is attempted on a
  38. * full buffer, then the thread will block until a space becomes available.
  39. * We would like to keep waiting <tt>put</tt> threads and <tt>take</tt>
  40. * threads in separate wait-sets so that we can use the optimization of
  41. * only notifying a single thread at a time when items or spaces become
  42. * available in the buffer. This can be achieved using two
  43. * {@link Condition} instances.
  44. * <pre>
  45. * class BoundedBuffer {
  46. * <b>final Lock lock = new ReentrantLock();</b>
  47. * final Condition notFull = <b>lock.newCondition(); </b>
  48. * final Condition notEmpty = <b>lock.newCondition(); </b>
  49. *
  50. * final Object[] items = new Object[100];
  51. * int putptr, takeptr, count;
  52. *
  53. * public void put(Object x) throws InterruptedException {
  54. * <b>lock.lock();
  55. * try {</b>
  56. * while (count == items.length)
  57. * <b>notFull.await();</b>
  58. * items[putptr] = x;
  59. * if (++putptr == items.length) putptr = 0;
  60. * ++count;
  61. * <b>notEmpty.signal();</b>
  62. * <b>} finally {
  63. * lock.unlock();
  64. * }</b>
  65. * }
  66. *
  67. * public Object take() throws InterruptedException {
  68. * <b>lock.lock();
  69. * try {</b>
  70. * while (count == 0)
  71. * <b>notEmpty.await();</b>
  72. * Object x = items[takeptr];
  73. * if (++takeptr == items.length) takeptr = 0;
  74. * --count;
  75. * <b>notFull.signal();</b>
  76. * return x;
  77. * <b>} finally {
  78. * lock.unlock();
  79. * }</b>
  80. * }
  81. * }
  82. * </pre>
  83. *
  84. * (The {@link java.util.concurrent.ArrayBlockingQueue} class provides
  85. * this functionality, so there is no reason to implement this
  86. * sample usage class.)
  87. *
  88. * <p>A <tt>Condition</tt> implementation can provide behavior and semantics
  89. * that is
  90. * different from that of the <tt>Object</tt> monitor methods, such as
  91. * guaranteed ordering for notifications, or not requiring a lock to be held
  92. * when performing notifications.
  93. * If an implementation provides such specialized semantics then the
  94. * implementation must document those semantics.
  95. *
  96. * <p>Note that <tt>Condition</tt> instances are just normal objects and can
  97. * themselves be used as the target in a <tt>synchronized</tt> statement,
  98. * and can have their own monitor {@link Object#wait wait} and
  99. * {@link Object#notify notification} methods invoked.
  100. * Acquiring the monitor lock of a <tt>Condition</tt> instance, or using its
  101. * monitor methods, has no specified relationship with acquiring the
  102. * {@link Lock} associated with that <tt>Condition</tt> or the use of its
  103. * {@link #await waiting} and {@link #signal signalling} methods.
  104. * It is recommended that to avoid confusion you never use <tt>Condition</tt>
  105. * instances in this way, except perhaps within their own implementation.
  106. *
  107. * <p>Except where noted, passing a <tt>null</tt> value for any parameter
  108. * will result in a {@link NullPointerException} being thrown.
  109. *
  110. * <h3>Implementation Considerations</h3>
  111. *
  112. * <p>When waiting upon a <tt>Condition</tt>, a "<em>spurious
  113. * wakeup</em>" is permitted to occur, in
  114. * general, as a concession to the underlying platform semantics.
  115. * This has little practical impact on most application programs as a
  116. * <tt>Condition</tt> should always be waited upon in a loop, testing
  117. * the state predicate that is being waited for. An implementation is
  118. * free to remove the possibility of spurious wakeups but it is
  119. * recommended that applications programmers always assume that they can
  120. * occur and so always wait in a loop.
  121. *
  122. * <p>The three forms of condition waiting
  123. * (interruptible, non-interruptible, and timed) may differ in their ease of
  124. * implementation on some platforms and in their performance characteristics.
  125. * In particular, it may be difficult to provide these features and maintain
  126. * specific semantics such as ordering guarantees.
  127. * Further, the ability to interrupt the actual suspension of the thread may
  128. * not always be feasible to implement on all platforms.
  129. * <p>Consequently, an implementation is not required to define exactly the
  130. * same guarantees or semantics for all three forms of waiting, nor is it
  131. * required to support interruption of the actual suspension of the thread.
  132. * <p>An implementation is required to
  133. * clearly document the semantics and guarantees provided by each of the
  134. * waiting methods, and when an implementation does support interruption of
  135. * thread suspension then it must obey the interruption semantics as defined
  136. * in this interface.
  137. * <p>As interruption generally implies cancellation, and checks for
  138. * interruption are often infrequent, an implementation can favor responding
  139. * to an interrupt over normal method return. This is true even if it can be
  140. * shown that the interrupt occurred after another action may have unblocked
  141. * the thread. An implementation should document this behavior.
  142. *
  143. *
  144. * @since 1.5
  145. * @author Doug Lea
  146. */
  147. public interface Condition {
  148. /**
  149. * Causes the current thread to wait until it is signalled or
  150. * {@link Thread#interrupt interrupted}.
  151. *
  152. * <p>The lock associated with this <tt>Condition</tt> is atomically
  153. * released and the current thread becomes disabled for thread scheduling
  154. * purposes and lies dormant until <em>one</em> of four things happens:
  155. * <ul>
  156. * <li>Some other thread invokes the {@link #signal} method for this
  157. * <tt>Condition</tt> and the current thread happens to be chosen as the
  158. * thread to be awakened; or
  159. * <li>Some other thread invokes the {@link #signalAll} method for this
  160. * <tt>Condition</tt> or
  161. * <li>Some other thread {@link Thread#interrupt interrupts} the current
  162. * thread, and interruption of thread suspension is supported; or
  163. * <li>A "<em>spurious wakeup</em>" occurs
  164. * </ul>
  165. *
  166. * <p>In all cases, before this method can return the current thread must
  167. * re-acquire the lock associated with this condition. When the
  168. * thread returns it is <em>guaranteed</em> to hold this lock.
  169. *
  170. * <p>If the current thread:
  171. * <ul>
  172. * <li>has its interrupted status set on entry to this method; or
  173. * <li>is {@link Thread#interrupt interrupted} while waiting
  174. * and interruption of thread suspension is supported,
  175. * </ul>
  176. * then {@link InterruptedException} is thrown and the current thread's
  177. * interrupted status is cleared. It is not specified, in the first
  178. * case, whether or not the test for interruption occurs before the lock
  179. * is released.
  180. *
  181. * <p><b>Implementation Considerations</b>
  182. * <p>The current thread is assumed to hold the lock associated with this
  183. * <tt>Condition</tt> when this method is called.
  184. * It is up to the implementation to determine if this is
  185. * the case and if not, how to respond. Typically, an exception will be
  186. * thrown (such as {@link IllegalMonitorStateException}) and the
  187. * implementation must document that fact.
  188. *
  189. * <p>An implementation can favor responding to an interrupt over normal
  190. * method return in response to a signal. In that case the implementation
  191. * must ensure that the signal is redirected to another waiting thread, if
  192. * there is one.
  193. *
  194. * @throws InterruptedException if the current thread is interrupted (and
  195. * interruption of thread suspension is supported).
  196. **/
  197. void await() throws InterruptedException;
  198. /**
  199. * Causes the current thread to wait until it is signalled.
  200. *
  201. * <p>The lock associated with this condition is atomically
  202. * released and the current thread becomes disabled for thread scheduling
  203. * purposes and lies dormant until <em>one</em> of three things happens:
  204. * <ul>
  205. * <li>Some other thread invokes the {@link #signal} method for this
  206. * <tt>Condition</tt> and the current thread happens to be chosen as the
  207. * thread to be awakened; or
  208. * <li>Some other thread invokes the {@link #signalAll} method for this
  209. * <tt>Condition</tt> or
  210. * <li>A "<em>spurious wakeup</em>" occurs
  211. * </ul>
  212. *
  213. * <p>In all cases, before this method can return the current thread must
  214. * re-acquire the lock associated with this condition. When the
  215. * thread returns it is <em>guaranteed</em> to hold this lock.
  216. *
  217. * <p>If the current thread's interrupted status is set when it enters
  218. * this method, or it is {@link Thread#interrupt interrupted}
  219. * while waiting, it will continue to wait until signalled. When it finally
  220. * returns from this method its interrupted status will still
  221. * be set.
  222. *
  223. * <p><b>Implementation Considerations</b>
  224. * <p>The current thread is assumed to hold the lock associated with this
  225. * <tt>Condition</tt> when this method is called.
  226. * It is up to the implementation to determine if this is
  227. * the case and if not, how to respond. Typically, an exception will be
  228. * thrown (such as {@link IllegalMonitorStateException}) and the
  229. * implementation must document that fact.
  230. *
  231. **/
  232. void awaitUninterruptibly();
  233. /**
  234. * Causes the current thread to wait until it is signalled or interrupted,
  235. * or the specified waiting time elapses.
  236. *
  237. * <p>The lock associated with this condition is atomically
  238. * released and the current thread becomes disabled for thread scheduling
  239. * purposes and lies dormant until <em>one</em> of five things happens:
  240. * <ul>
  241. * <li>Some other thread invokes the {@link #signal} method for this
  242. * <tt>Condition</tt> and the current thread happens to be chosen as the
  243. * thread to be awakened; or
  244. * <li>Some other thread invokes the {@link #signalAll} method for this
  245. * <tt>Condition</tt> or
  246. * <li>Some other thread {@link Thread#interrupt interrupts} the current
  247. * thread, and interruption of thread suspension is supported; or
  248. * <li>The specified waiting time elapses; or
  249. * <li>A "<em>spurious wakeup</em>" occurs.
  250. * </ul>
  251. *
  252. * <p>In all cases, before this method can return the current thread must
  253. * re-acquire the lock associated with this condition. When the
  254. * thread returns it is <em>guaranteed</em> to hold this lock.
  255. *
  256. * <p>If the current thread:
  257. * <ul>
  258. * <li>has its interrupted status set on entry to this method; or
  259. * <li>is {@link Thread#interrupt interrupted} while waiting
  260. * and interruption of thread suspension is supported,
  261. * </ul>
  262. * then {@link InterruptedException} is thrown and the current thread's
  263. * interrupted status is cleared. It is not specified, in the first
  264. * case, whether or not the test for interruption occurs before the lock
  265. * is released.
  266. *
  267. * <p>The method returns an estimate of the number of nanoseconds
  268. * remaining to wait given the supplied <tt>nanosTimeout</tt>
  269. * value upon return, or a value less than or equal to zero if it
  270. * timed out. This value can be used to determine whether and how
  271. * long to re-wait in cases where the wait returns but an awaited
  272. * condition still does not hold. Typical uses of this method take
  273. * the following form:
  274. *
  275. * <pre>
  276. * synchronized boolean aMethod(long timeout, TimeUnit unit) {
  277. * long nanosTimeout = unit.toNanos(timeout);
  278. * while (!conditionBeingWaitedFor) {
  279. * if (nanosTimeout > 0)
  280. * nanosTimeout = theCondition.awaitNanos(nanosTimeout);
  281. * else
  282. * return false;
  283. * }
  284. * // ...
  285. * }
  286. * </pre>
  287. *
  288. * <p> Design note: This method requires a nanosecond argument so
  289. * as to avoid truncation errors in reporting remaining times.
  290. * Such precision loss would make it difficult for programmers to
  291. * ensure that total waiting times are not systematically shorter
  292. * than specified when re-waits occur.
  293. *
  294. * <p><b>Implementation Considerations</b>
  295. * <p>The current thread is assumed to hold the lock associated with this
  296. * <tt>Condition</tt> when this method is called.
  297. * It is up to the implementation to determine if this is
  298. * the case and if not, how to respond. Typically, an exception will be
  299. * thrown (such as {@link IllegalMonitorStateException}) and the
  300. * implementation must document that fact.
  301. *
  302. * <p>An implementation can favor responding to an interrupt over normal
  303. * method return in response to a signal, or over indicating the elapse
  304. * of the specified waiting time. In either case the implementation
  305. * must ensure that the signal is redirected to another waiting thread, if
  306. * there is one.
  307. *
  308. * @param nanosTimeout the maximum time to wait, in nanoseconds
  309. * @return A value less than or equal to zero if the wait has
  310. * timed out; otherwise an estimate, that
  311. * is strictly less than the <tt>nanosTimeout</tt> argument,
  312. * of the time still remaining when this method returned.
  313. *
  314. * @throws InterruptedException if the current thread is interrupted (and
  315. * interruption of thread suspension is supported).
  316. */
  317. long awaitNanos(long nanosTimeout) throws InterruptedException;
  318. /**
  319. * Causes the current thread to wait until it is signalled or interrupted,
  320. * or the specified waiting time elapses. This method is behaviorally
  321. * equivalent to:<br>
  322. * <pre>
  323. * awaitNanos(unit.toNanos(time)) > 0
  324. * </pre>
  325. * @param time the maximum time to wait
  326. * @param unit the time unit of the <tt>time</tt> argument.
  327. * @return <tt>false</tt> if the waiting time detectably elapsed
  328. * before return from the method, else <tt>true</tt>.
  329. * @throws InterruptedException if the current thread is interrupted (and
  330. * interruption of thread suspension is supported).
  331. */
  332. boolean await(long time, TimeUnit unit) throws InterruptedException;
  333. /**
  334. * Causes the current thread to wait until it is signalled or interrupted,
  335. * or the specified deadline elapses.
  336. *
  337. * <p>The lock associated with this condition is atomically
  338. * released and the current thread becomes disabled for thread scheduling
  339. * purposes and lies dormant until <em>one</em> of five things happens:
  340. * <ul>
  341. * <li>Some other thread invokes the {@link #signal} method for this
  342. * <tt>Condition</tt> and the current thread happens to be chosen as the
  343. * thread to be awakened; or
  344. * <li>Some other thread invokes the {@link #signalAll} method for this
  345. * <tt>Condition</tt> or
  346. * <li>Some other thread {@link Thread#interrupt interrupts} the current
  347. * thread, and interruption of thread suspension is supported; or
  348. * <li>The specified deadline elapses; or
  349. * <li>A "<em>spurious wakeup</em>" occurs.
  350. * </ul>
  351. *
  352. * <p>In all cases, before this method can return the current thread must
  353. * re-acquire the lock associated with this condition. When the
  354. * thread returns it is <em>guaranteed</em> to hold this lock.
  355. *
  356. *
  357. * <p>If the current thread:
  358. * <ul>
  359. * <li>has its interrupted status set on entry to this method; or
  360. * <li>is {@link Thread#interrupt interrupted} while waiting
  361. * and interruption of thread suspension is supported,
  362. * </ul>
  363. * then {@link InterruptedException} is thrown and the current thread's
  364. * interrupted status is cleared. It is not specified, in the first
  365. * case, whether or not the test for interruption occurs before the lock
  366. * is released.
  367. *
  368. *
  369. * <p>The return value indicates whether the deadline has elapsed,
  370. * which can be used as follows:
  371. * <pre>
  372. * synchronized boolean aMethod(Date deadline) {
  373. * boolean stillWaiting = true;
  374. * while (!conditionBeingWaitedFor) {
  375. * if (stillwaiting)
  376. * stillWaiting = theCondition.awaitUntil(deadline);
  377. * else
  378. * return false;
  379. * }
  380. * // ...
  381. * }
  382. * </pre>
  383. *
  384. * <p><b>Implementation Considerations</b>
  385. * <p>The current thread is assumed to hold the lock associated with this
  386. * <tt>Condition</tt> when this method is called.
  387. * It is up to the implementation to determine if this is
  388. * the case and if not, how to respond. Typically, an exception will be
  389. * thrown (such as {@link IllegalMonitorStateException}) and the
  390. * implementation must document that fact.
  391. *
  392. * <p>An implementation can favor responding to an interrupt over normal
  393. * method return in response to a signal, or over indicating the passing
  394. * of the specified deadline. In either case the implementation
  395. * must ensure that the signal is redirected to another waiting thread, if
  396. * there is one.
  397. *
  398. *
  399. * @param deadline the absolute time to wait until
  400. * @return <tt>false</tt> if the deadline has
  401. * elapsed upon return, else <tt>true</tt>.
  402. *
  403. * @throws InterruptedException if the current thread is interrupted (and
  404. * interruption of thread suspension is supported).
  405. */
  406. boolean awaitUntil(Date deadline) throws InterruptedException;
  407. /**
  408. * Wakes up one waiting thread.
  409. *
  410. * <p>If any threads are waiting on this condition then one
  411. * is selected for waking up. That thread must then re-acquire the
  412. * lock before returning from <tt>await</tt>.
  413. **/
  414. void signal();
  415. /**
  416. * Wakes up all waiting threads.
  417. *
  418. * <p>If any threads are waiting on this condition then they are
  419. * all woken up. Each thread must re-acquire the lock before it can
  420. * return from <tt>await</tt>.
  421. **/
  422. void signalAll();
  423. }