1. /*
  2. File: Mutex.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. */
  11. package com.sun.corba.se.impl.orbutil.concurrent;
  12. import com.sun.corba.se.impl.orbutil.ORBUtility ;
  13. /**
  14. * A simple reentrant mutual exclusion lock.
  15. * The lock is free upon construction. Each acquire gets the
  16. * lock, and each release frees it. Releasing a lock that
  17. * is already free has no effect.
  18. * <p>
  19. * This implementation makes no attempt to provide any fairness
  20. * or ordering guarantees. If you need them, consider using one of
  21. * the Semaphore implementations as a locking mechanism.
  22. * <p>
  23. * <b>Sample usage</b><br>
  24. * <p>
  25. * Mutex can be useful in constructions that cannot be
  26. * expressed using java synchronized blocks because the
  27. * acquire/release pairs do not occur in the same method or
  28. * code block. For example, you can use them for hand-over-hand
  29. * locking across the nodes of a linked list. This allows
  30. * extremely fine-grained locking, and so increases
  31. * potential concurrency, at the cost of additional complexity and
  32. * overhead that would normally make this worthwhile only in cases of
  33. * extreme contention.
  34. * <pre>
  35. * class Node {
  36. * Object item;
  37. * Node next;
  38. * Mutex lock = new Mutex(); // each node keeps its own lock
  39. *
  40. * Node(Object x, Node n) { item = x; next = n; }
  41. * }
  42. *
  43. * class List {
  44. * protected Node head; // pointer to first node of list
  45. *
  46. * // Use plain java synchronization to protect head field.
  47. * // (We could instead use a Mutex here too but there is no
  48. * // reason to do so.)
  49. * protected synchronized Node getHead() { return head; }
  50. *
  51. * boolean search(Object x) throws InterruptedException {
  52. * Node p = getHead();
  53. * if (p == null) return false;
  54. *
  55. * // (This could be made more compact, but for clarity of illustration,
  56. * // all of the cases that can arise are handled separately.)
  57. *
  58. * p.lock.acquire(); // Prime loop by acquiring first lock.
  59. * // (If the acquire fails due to
  60. * // interrupt, the method will throw
  61. * // InterruptedException now,
  62. * // so there is no need for any
  63. * // further cleanup.)
  64. * for (;;) {
  65. * if (x.equals(p.item)) {
  66. * p.lock.release(); // release current before return
  67. * return true;
  68. * }
  69. * else {
  70. * Node nextp = p.next;
  71. * if (nextp == null) {
  72. * p.lock.release(); // release final lock that was held
  73. * return false;
  74. * }
  75. * else {
  76. * try {
  77. * nextp.lock.acquire(); // get next lock before releasing current
  78. * }
  79. * catch (InterruptedException ex) {
  80. * p.lock.release(); // also release current if acquire fails
  81. * throw ex;
  82. * }
  83. * p.lock.release(); // release old lock now that new one held
  84. * p = nextp;
  85. * }
  86. * }
  87. * }
  88. * }
  89. *
  90. * synchronized void add(Object x) { // simple prepend
  91. * // The use of `synchronized' here protects only head field.
  92. * // The method does not need to wait out other traversers
  93. * // who have already made it past head.
  94. *
  95. * head = new Node(x, head);
  96. * }
  97. *
  98. * // ... other similar traversal and update methods ...
  99. * }
  100. * </pre>
  101. * <p>
  102. * <p>This version adds some debugging capability: it will detect
  103. * an attempt by a thread that does not hold the mutex to release it.
  104. * This version is reentrant: the same thread may acquire a mutex multiple
  105. * times, in which case it must release the mutex the same number of times
  106. * as it was acquired before another thread can acquire the mutex.
  107. * @see Semaphore
  108. * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
  109. **/
  110. import org.omg.CORBA.INTERNAL ;
  111. public class ReentrantMutex implements Sync {
  112. /** The thread holding the lock **/
  113. protected Thread holder_ = null;
  114. /** number of times thread has acquired the lock **/
  115. protected int counter_ = 0 ;
  116. protected boolean debug = false ;
  117. public ReentrantMutex()
  118. {
  119. this( false ) ;
  120. }
  121. public ReentrantMutex( boolean debug )
  122. {
  123. this.debug = debug ;
  124. }
  125. public void acquire() throws InterruptedException {
  126. if (Thread.interrupted())
  127. throw new InterruptedException();
  128. synchronized(this) {
  129. try {
  130. if (debug)
  131. ORBUtility.dprintTrace( this,
  132. "acquire enter: holder_=" +
  133. ORBUtility.getThreadName(holder_) +
  134. " counter_=" + counter_ ) ;
  135. Thread thr = Thread.currentThread();
  136. if (holder_ != thr) {
  137. try {
  138. while (counter_ > 0)
  139. wait();
  140. // This can't happen, but make sure anyway
  141. if (counter_ != 0)
  142. throw new INTERNAL(
  143. "counter not 0 when first acquiring mutex" ) ;
  144. holder_ = thr;
  145. } catch (InterruptedException ex) {
  146. notify();
  147. throw ex;
  148. }
  149. }
  150. counter_ ++ ;
  151. } finally {
  152. if (debug)
  153. ORBUtility.dprintTrace( this, "acquire exit: holder_=" +
  154. ORBUtility.getThreadName(holder_) + " counter_=" +
  155. counter_ ) ;
  156. }
  157. }
  158. }
  159. void acquireAll( int count ) throws InterruptedException
  160. {
  161. if (Thread.interrupted())
  162. throw new InterruptedException();
  163. synchronized(this) {
  164. try {
  165. if (debug)
  166. ORBUtility.dprintTrace( this,
  167. "acquireAll enter: count=" + count + " holder_=" +
  168. ORBUtility.getThreadName(holder_) + " counter_=" +
  169. counter_ ) ;
  170. Thread thr = Thread.currentThread();
  171. if (holder_ == thr) {
  172. throw new INTERNAL(
  173. "Cannot acquireAll while holding the mutex" ) ;
  174. } else {
  175. try {
  176. while (counter_ > 0)
  177. wait();
  178. // This can't happen, but make sure anyway
  179. if (counter_ != 0)
  180. throw new INTERNAL(
  181. "counter not 0 when first acquiring mutex" ) ;
  182. holder_ = thr;
  183. } catch (InterruptedException ex) {
  184. notify();
  185. throw ex;
  186. }
  187. }
  188. counter_ = count ;
  189. } finally {
  190. if (debug)
  191. ORBUtility.dprintTrace( this, "acquireAll exit: count=" +
  192. count + " holder_=" + ORBUtility.getThreadName(holder_) +
  193. " counter_=" + counter_ ) ;
  194. }
  195. }
  196. }
  197. public synchronized void release()
  198. {
  199. try {
  200. if (debug)
  201. ORBUtility.dprintTrace( this, "release enter: " +
  202. " holder_=" + ORBUtility.getThreadName(holder_) +
  203. " counter_=" + counter_ ) ;
  204. Thread thr = Thread.currentThread();
  205. if (thr != holder_)
  206. throw new INTERNAL(
  207. "Attempt to release Mutex by thread not holding the Mutex" ) ;
  208. else
  209. counter_ -- ;
  210. if (counter_ == 0) {
  211. holder_ = null;
  212. notify();
  213. }
  214. } finally {
  215. if (debug)
  216. ORBUtility.dprintTrace( this, "release exit: " +
  217. " holder_=" + ORBUtility.getThreadName(holder_) +
  218. " counter_=" + counter_ ) ;
  219. }
  220. }
  221. synchronized int releaseAll()
  222. {
  223. try {
  224. if (debug)
  225. ORBUtility.dprintTrace( this, "releaseAll enter: " +
  226. " holder_=" + ORBUtility.getThreadName(holder_) +
  227. " counter_=" + counter_ ) ;
  228. Thread thr = Thread.currentThread();
  229. if (thr != holder_)
  230. throw new INTERNAL(
  231. "Attempt to releaseAll Mutex by thread not holding the Mutex" ) ;
  232. int result = counter_ ;
  233. counter_ = 0 ;
  234. holder_ = null ;
  235. notify() ;
  236. return result ;
  237. } finally {
  238. if (debug)
  239. ORBUtility.dprintTrace( this, "releaseAll exit: " +
  240. " holder_=" + ORBUtility.getThreadName(holder_) +
  241. " counter_=" + counter_ ) ;
  242. }
  243. }
  244. public boolean attempt(long msecs) throws InterruptedException {
  245. if (Thread.interrupted())
  246. throw new InterruptedException();
  247. synchronized(this) {
  248. try {
  249. if (debug)
  250. ORBUtility.dprintTrace( this, "attempt enter: msecs=" +
  251. msecs + " holder_=" +
  252. ORBUtility.getThreadName(holder_) +
  253. " counter_=" + counter_ ) ;
  254. Thread thr = Thread.currentThread() ;
  255. if (counter_==0) {
  256. holder_ = thr;
  257. counter_ = 1 ;
  258. return true;
  259. } else if (msecs <= 0) {
  260. return false;
  261. } else {
  262. long waitTime = msecs;
  263. long start = System.currentTimeMillis();
  264. try {
  265. for (;;) {
  266. wait(waitTime);
  267. if (counter_==0) {
  268. holder_ = thr;
  269. counter_ = 1 ;
  270. return true;
  271. } else {
  272. waitTime = msecs -
  273. (System.currentTimeMillis() - start);
  274. if (waitTime <= 0)
  275. return false;
  276. }
  277. }
  278. } catch (InterruptedException ex) {
  279. notify();
  280. throw ex;
  281. }
  282. }
  283. } finally {
  284. if (debug)
  285. ORBUtility.dprintTrace( this, "attempt exit: " +
  286. " holder_=" + ORBUtility.getThreadName(holder_) +
  287. " counter_=" + counter_ ) ;
  288. }
  289. }
  290. }
  291. }