1. /*
  2. File: ConditionVariable.java
  3. Originally written by Doug Lea and released into the public domain.
  4. This may be used for any purposes whatsoever without acknowledgment.
  5. Thanks for the assistance and support of Sun Microsystems Labs,
  6. and everyone contributing, testing, and using this code.
  7. History:
  8. Date Who What
  9. 11Jun1998 dl Create public version
  10. 08dec2001 kmc Added support for Reentrant Mutexes
  11. */
  12. package com.sun.corba.se.impl.orbutil.concurrent;
  13. import com.sun.corba.se.impl.orbutil.ORBUtility ;
  14. /**
  15. * This class is designed for fans of POSIX pthreads programming.
  16. * If you restrict yourself to Mutexes and CondVars, you can
  17. * use most of your favorite constructions. Don't randomly mix them
  18. * with synchronized methods or blocks though.
  19. * <p>
  20. * Method names and behavior are as close as is reasonable to
  21. * those in POSIX.
  22. * <p>
  23. * <b>Sample Usage.</b> Here is a full version of a bounded buffer
  24. * that implements the BoundedChannel interface, written in
  25. * a style reminscent of that in POSIX programming books.
  26. * <pre>
  27. * class CVBuffer implements BoundedChannel {
  28. * private final Mutex mutex;
  29. * private final CondVar notFull;
  30. * private final CondVar notEmpty;
  31. * private int count = 0;
  32. * private int takePtr = 0;
  33. * private int putPtr = 0;
  34. * private final Object[] array;
  35. *
  36. * public CVBuffer(int capacity) {
  37. * array = new Object[capacity];
  38. * mutex = new Mutex();
  39. * notFull = new CondVar(mutex);
  40. * notEmpty = new CondVar(mutex);
  41. * }
  42. *
  43. * public int capacity() { return array.length; }
  44. *
  45. * public void put(Object x) throws InterruptedException {
  46. * mutex.acquire();
  47. * try {
  48. * while (count == array.length) {
  49. * notFull.await();
  50. * }
  51. * array[putPtr] = x;
  52. * putPtr = (putPtr + 1) % array.length;
  53. * ++count;
  54. * notEmpty.signal();
  55. * }
  56. * finally {
  57. * mutex.release();
  58. * }
  59. * }
  60. *
  61. * public Object take() throws InterruptedException {
  62. * Object x = null;
  63. * mutex.acquire();
  64. * try {
  65. * while (count == 0) {
  66. * notEmpty.await();
  67. * }
  68. * x = array[takePtr];
  69. * array[takePtr] = null;
  70. * takePtr = (takePtr + 1) % array.length;
  71. * --count;
  72. * notFull.signal();
  73. * }
  74. * finally {
  75. * mutex.release();
  76. * }
  77. * return x;
  78. * }
  79. *
  80. * public boolean offer(Object x, long msecs) throws InterruptedException {
  81. * mutex.acquire();
  82. * try {
  83. * if (count == array.length) {
  84. * notFull.timedwait(msecs);
  85. * if (count == array.length)
  86. * return false;
  87. * }
  88. * array[putPtr] = x;
  89. * putPtr = (putPtr + 1) % array.length;
  90. * ++count;
  91. * notEmpty.signal();
  92. * return true;
  93. * }
  94. * finally {
  95. * mutex.release();
  96. * }
  97. * }
  98. *
  99. * public Object poll(long msecs) throws InterruptedException {
  100. * Object x = null;
  101. * mutex.acquire();
  102. * try {
  103. * if (count == 0) {
  104. * notEmpty.timedwait(msecs);
  105. * if (count == 0)
  106. * return null;
  107. * }
  108. * x = array[takePtr];
  109. * array[takePtr] = null;
  110. * takePtr = (takePtr + 1) % array.length;
  111. * --count;
  112. * notFull.signal();
  113. * }
  114. * finally {
  115. * mutex.release();
  116. * }
  117. * return x;
  118. * }
  119. * }
  120. *
  121. * </pre>
  122. * @see Mutex
  123. * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
  124. **/
  125. public class CondVar {
  126. protected boolean debug_ ;
  127. /** The mutex **/
  128. protected final Sync mutex_;
  129. protected final ReentrantMutex remutex_;
  130. private int releaseMutex()
  131. {
  132. int count = 1 ;
  133. if (remutex_!=null)
  134. count = remutex_.releaseAll() ;
  135. else
  136. mutex_.release() ;
  137. return count ;
  138. }
  139. private void acquireMutex( int count ) throws InterruptedException
  140. {
  141. if (remutex_!=null)
  142. remutex_.acquireAll( count ) ;
  143. else
  144. mutex_.acquire() ;
  145. }
  146. /**
  147. * Create a new CondVar that relies on the given mutual
  148. * exclusion lock.
  149. * @param mutex A mutual exclusion lock which must either be non-reentrant,
  150. * or else be ReentrantMutex.
  151. * Standard usage is to supply an instance of <code>Mutex</code>,
  152. * but, for example, a Semaphore initialized to 1 also works.
  153. * On the other hand, many other Sync implementations would not
  154. * work here, so some care is required to supply a sensible
  155. * synchronization object.
  156. * In normal use, the mutex should be one that is used for <em>all</em>
  157. * synchronization of the object using the CondVar. Generally,
  158. * to prevent nested monitor lockouts, this
  159. * object should not use any native Java synchronized blocks.
  160. **/
  161. public CondVar(Sync mutex, boolean debug) {
  162. debug_ = debug ;
  163. mutex_ = mutex;
  164. if (mutex instanceof ReentrantMutex)
  165. remutex_ = (ReentrantMutex)mutex;
  166. else
  167. remutex_ = null;
  168. }
  169. public CondVar( Sync mutex ) {
  170. this( mutex, false ) ;
  171. }
  172. /**
  173. * Wait for notification. This operation at least momentarily
  174. * releases the mutex. The mutex is always held upon return,
  175. * even if interrupted.
  176. * @exception InterruptedException if the thread was interrupted
  177. * before or during the wait. However, if the thread is interrupted
  178. * after the wait but during mutex re-acquisition, the interruption
  179. * is ignored, while still ensuring
  180. * that the currentThread's interruption state stays true, so can
  181. * be probed by callers.
  182. **/
  183. public void await() throws InterruptedException {
  184. int count = 0 ;
  185. if (Thread.interrupted())
  186. throw new InterruptedException();
  187. try {
  188. if (debug_)
  189. ORBUtility.dprintTrace( this, "await enter" ) ;
  190. synchronized(this) {
  191. count = releaseMutex() ;
  192. try {
  193. wait();
  194. } catch (InterruptedException ex) {
  195. notify();
  196. throw ex;
  197. }
  198. }
  199. } finally {
  200. // Must ignore interrupt on re-acquire
  201. boolean interrupted = false;
  202. for (;;) {
  203. try {
  204. acquireMutex( count );
  205. break;
  206. } catch (InterruptedException ex) {
  207. interrupted = true;
  208. }
  209. }
  210. if (interrupted) {
  211. Thread.currentThread().interrupt();
  212. }
  213. if (debug_)
  214. ORBUtility.dprintTrace( this, "await exit" ) ;
  215. }
  216. }
  217. /**
  218. * Wait for at most msecs for notification.
  219. * This operation at least momentarily
  220. * releases the mutex. The mutex is always held upon return,
  221. * even if interrupted.
  222. * @param msecs The time to wait. A value less than or equal to zero
  223. * causes a momentarily release
  224. * and re-acquire of the mutex, and always returns false.
  225. * @return false if at least msecs have elapsed
  226. * upon resumption; else true. A
  227. * false return does NOT necessarily imply that the thread was
  228. * not notified. For example, it might have been notified
  229. * after the time elapsed but just before resuming.
  230. * @exception InterruptedException if the thread was interrupted
  231. * before or during the wait.
  232. **/
  233. public boolean timedwait(long msecs) throws InterruptedException {
  234. if (Thread.interrupted())
  235. throw new InterruptedException();
  236. boolean success = false;
  237. int count = 0;
  238. try {
  239. if (debug_)
  240. ORBUtility.dprintTrace( this, "timedwait enter" ) ;
  241. synchronized(this) {
  242. count = releaseMutex() ;
  243. try {
  244. if (msecs > 0) {
  245. long start = System.currentTimeMillis();
  246. wait(msecs);
  247. success = System.currentTimeMillis() - start <= msecs;
  248. }
  249. } catch (InterruptedException ex) {
  250. notify();
  251. throw ex;
  252. }
  253. }
  254. } finally {
  255. // Must ignore interrupt on re-acquire
  256. boolean interrupted = false;
  257. for (;;) {
  258. try {
  259. acquireMutex( count ) ;
  260. break;
  261. } catch (InterruptedException ex) {
  262. interrupted = true;
  263. }
  264. }
  265. if (interrupted) {
  266. Thread.currentThread().interrupt();
  267. }
  268. if (debug_)
  269. ORBUtility.dprintTrace( this, "timedwait exit" ) ;
  270. }
  271. return success;
  272. }
  273. /**
  274. * Notify a waiting thread.
  275. * If one exists, a non-interrupted thread will return
  276. * normally (i.e., not via InterruptedException) from await or timedwait.
  277. **/
  278. public synchronized void signal() {
  279. notify();
  280. }
  281. /** Notify all waiting threads **/
  282. public synchronized void broadcast() {
  283. notifyAll();
  284. }
  285. }