1. /*
  2. File: Sync.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. 5Aug1998 dl Added some convenient time constants
  11. */
  12. package com.sun.corba.se.impl.orbutil.concurrent;
  13. /**
  14. * Main interface for locks, gates, and conditions.
  15. * <p>
  16. * Sync objects isolate waiting and notification for particular
  17. * logical states, resource availability, events, and the like that are
  18. * shared across multiple threads. Use of Syncs sometimes
  19. * (but by no means always) adds flexibility and efficiency
  20. * compared to the use of plain java monitor methods
  21. * and locking, and are sometimes (but by no means always)
  22. * simpler to program with.
  23. * <p>
  24. *
  25. * Most Syncs are intended to be used primarily (although
  26. * not exclusively) in before/after constructions such as:
  27. * <pre>
  28. * class X {
  29. * Sync gate;
  30. * // ...
  31. *
  32. * public void m() {
  33. * try {
  34. * gate.acquire(); // block until condition holds
  35. * try {
  36. * // ... method body
  37. * }
  38. * finally {
  39. * gate.release()
  40. * }
  41. * }
  42. * catch (InterruptedException ex) {
  43. * // ... evasive action
  44. * }
  45. * }
  46. *
  47. * public void m2(Sync cond) { // use supplied condition
  48. * try {
  49. * if (cond.attempt(10)) { // try the condition for 10 ms
  50. * try {
  51. * // ... method body
  52. * }
  53. * finally {
  54. * cond.release()
  55. * }
  56. * }
  57. * }
  58. * catch (InterruptedException ex) {
  59. * // ... evasive action
  60. * }
  61. * }
  62. * }
  63. * </pre>
  64. * Syncs may be used in somewhat tedious but more flexible replacements
  65. * for built-in Java synchronized blocks. For example:
  66. * <pre>
  67. * class HandSynched {
  68. * private double state_ = 0.0;
  69. * private final Sync lock; // use lock type supplied in constructor
  70. * public HandSynched(Sync l) { lock = l; }
  71. *
  72. * public void changeState(double d) {
  73. * try {
  74. * lock.acquire();
  75. * try { state_ = updateFunction(d); }
  76. * finally { lock.release(); }
  77. * }
  78. * catch(InterruptedException ex) { }
  79. * }
  80. *
  81. * public double getState() {
  82. * double d = 0.0;
  83. * try {
  84. * lock.acquire();
  85. * try { d = accessFunction(state_); }
  86. * finally { lock.release(); }
  87. * }
  88. * catch(InterruptedException ex){}
  89. * return d;
  90. * }
  91. * private double updateFunction(double d) { ... }
  92. * private double accessFunction(double d) { ... }
  93. * }
  94. * </pre>
  95. * If you have a lot of such methods, and they take a common
  96. * form, you can standardize this using wrappers. Some of these
  97. * wrappers are standardized in LockedExecutor, but you can make others.
  98. * For example:
  99. * <pre>
  100. * class HandSynchedV2 {
  101. * private double state_ = 0.0;
  102. * private final Sync lock; // use lock type supplied in constructor
  103. * public HandSynchedV2(Sync l) { lock = l; }
  104. *
  105. * protected void runSafely(Runnable r) {
  106. * try {
  107. * lock.acquire();
  108. * try { r.run(); }
  109. * finally { lock.release(); }
  110. * }
  111. * catch (InterruptedException ex) { // propagate without throwing
  112. * Thread.currentThread().interrupt();
  113. * }
  114. * }
  115. *
  116. * public void changeState(double d) {
  117. * runSafely(new Runnable() {
  118. * public void run() { state_ = updateFunction(d); }
  119. * });
  120. * }
  121. * // ...
  122. * }
  123. * </pre>
  124. * <p>
  125. * One reason to bother with such constructions is to use deadlock-
  126. * avoiding back-offs when dealing with locks involving multiple objects.
  127. * For example, here is a Cell class that uses attempt to back-off
  128. * and retry if two Cells are trying to swap values with each other
  129. * at the same time.
  130. * <pre>
  131. * class Cell {
  132. * long value;
  133. * Sync lock = ... // some sync implementation class
  134. * void swapValue(Cell other) {
  135. * for (;;) {
  136. * try {
  137. * lock.acquire();
  138. * try {
  139. * if (other.lock.attempt(100)) {
  140. * try {
  141. * long t = value;
  142. * value = other.value;
  143. * other.value = t;
  144. * return;
  145. * }
  146. * finally { other.lock.release(); }
  147. * }
  148. * }
  149. * finally { lock.release(); }
  150. * }
  151. * catch (InterruptedException ex) { return; }
  152. * }
  153. * }
  154. * }
  155. *</pre>
  156. * <p>
  157. * Here is an even fancier version, that uses lock re-ordering
  158. * upon conflict:
  159. * <pre>
  160. * class Cell {
  161. * long value;
  162. * Sync lock = ...;
  163. * private static boolean trySwap(Cell a, Cell b) {
  164. * a.lock.acquire();
  165. * try {
  166. * if (!b.lock.attempt(0))
  167. * return false;
  168. * try {
  169. * long t = a.value;
  170. * a.value = b.value;
  171. * b.value = t;
  172. * return true;
  173. * }
  174. * finally { other.lock.release(); }
  175. * }
  176. * finally { lock.release(); }
  177. * return false;
  178. * }
  179. *
  180. * void swapValue(Cell other) {
  181. * try {
  182. * while (!trySwap(this, other) &&
  183. * !tryswap(other, this))
  184. * Thread.sleep(1);
  185. * }
  186. * catch (InterruptedException ex) { return; }
  187. * }
  188. *}
  189. *</pre>
  190. * <p>
  191. * Interruptions are in general handled as early as possible.
  192. * Normally, InterruptionExceptions are thrown
  193. * in acquire and attempt(msec) if interruption
  194. * is detected upon entry to the method, as well as in any
  195. * later context surrounding waits.
  196. * However, interruption status is ignored in release();
  197. * <p>
  198. * Timed versions of attempt report failure via return value.
  199. * If so desired, you can transform such constructions to use exception
  200. * throws via
  201. * <pre>
  202. * if (!c.attempt(timeval)) throw new TimeoutException(timeval);
  203. * </pre>
  204. * <p>
  205. * The TimoutSync wrapper class can be used to automate such usages.
  206. * <p>
  207. * All time values are expressed in milliseconds as longs, which have a maximum
  208. * value of Long.MAX_VALUE, or almost 300,000 centuries. It is not
  209. * known whether JVMs actually deal correctly with such extreme values.
  210. * For convenience, some useful time values are defined as static constants.
  211. * <p>
  212. * All implementations of the three Sync methods guarantee to
  213. * somehow employ Java <code>synchronized</code> methods or blocks,
  214. * and so entail the memory operations described in JLS
  215. * chapter 17 which ensure that variables are loaded and flushed
  216. * within before/after constructions.
  217. * <p>
  218. * Syncs may also be used in spinlock constructions. Although
  219. * it is normally best to just use acquire(), various forms
  220. * of busy waits can be implemented. For a simple example
  221. * (but one that would probably never be preferable to using acquire()):
  222. * <pre>
  223. * class X {
  224. * Sync lock = ...
  225. * void spinUntilAcquired() throws InterruptedException {
  226. * // Two phase.
  227. * // First spin without pausing.
  228. * int purespins = 10;
  229. * for (int i = 0; i < purespins; ++i) {
  230. * if (lock.attempt(0))
  231. * return true;
  232. * }
  233. * // Second phase - use timed waits
  234. * long waitTime = 1; // 1 millisecond
  235. * for (;;) {
  236. * if (lock.attempt(waitTime))
  237. * return true;
  238. * else
  239. * waitTime = waitTime * 3 / 2 + 1; // increase 50%
  240. * }
  241. * }
  242. * }
  243. * </pre>
  244. * <p>
  245. * In addition pure synchronization control, Syncs
  246. * may be useful in any context requiring before/after methods.
  247. * For example, you can use an ObservableSync
  248. * (perhaps as part of a LayeredSync) in order to obtain callbacks
  249. * before and after each method invocation for a given class.
  250. * <p>
  251. * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
  252. **/
  253. public interface Sync {
  254. /**
  255. * Wait (possibly forever) until successful passage.
  256. * Fail only upon interuption. Interruptions always result in
  257. * `clean' failures. On failure, you can be sure that it has not
  258. * been acquired, and that no
  259. * corresponding release should be performed. Conversely,
  260. * a normal return guarantees that the acquire was successful.
  261. **/
  262. public void acquire() throws InterruptedException;
  263. /**
  264. * Wait at most msecs to pass; report whether passed.
  265. * <p>
  266. * The method has best-effort semantics:
  267. * The msecs bound cannot
  268. * be guaranteed to be a precise upper bound on wait time in Java.
  269. * Implementations generally can only attempt to return as soon as possible
  270. * after the specified bound. Also, timers in Java do not stop during garbage
  271. * collection, so timeouts can occur just because a GC intervened.
  272. * So, msecs arguments should be used in
  273. * a coarse-grained manner. Further,
  274. * implementations cannot always guarantee that this method
  275. * will return at all without blocking indefinitely when used in
  276. * unintended ways. For example, deadlocks may be encountered
  277. * when called in an unintended context.
  278. * <p>
  279. * @param msecs the number of milleseconds to wait.
  280. * An argument less than or equal to zero means not to wait at all.
  281. * However, this may still require
  282. * access to a synchronization lock, which can impose unbounded
  283. * delay if there is a lot of contention among threads.
  284. * @return true if acquired
  285. **/
  286. public boolean attempt(long msecs) throws InterruptedException;
  287. /**
  288. * Potentially enable others to pass.
  289. * <p>
  290. * Because release does not raise exceptions,
  291. * it can be used in `finally' clauses without requiring extra
  292. * embedded try/catch blocks. But keep in mind that
  293. * as with any java method, implementations may
  294. * still throw unchecked exceptions such as Error or NullPointerException
  295. * when faced with uncontinuable errors. However, these should normally
  296. * only be caught by higher-level error handlers.
  297. **/
  298. public void release();
  299. /** One second, in milliseconds; convenient as a time-out value **/
  300. public static final long ONE_SECOND = 1000;
  301. /** One minute, in milliseconds; convenient as a time-out value **/
  302. public static final long ONE_MINUTE = 60 * ONE_SECOND;
  303. /** One hour, in milliseconds; convenient as a time-out value **/
  304. public static final long ONE_HOUR = 60 * ONE_MINUTE;
  305. /** One day, in milliseconds; convenient as a time-out value **/
  306. public static final long ONE_DAY = 24 * ONE_HOUR;
  307. /** One week, in milliseconds; convenient as a time-out value **/
  308. public static final long ONE_WEEK = 7 * ONE_DAY;
  309. /** One year in milliseconds; convenient as a time-out value **/
  310. // Not that it matters, but there is some variation across
  311. // standard sources about value at msec precision.
  312. // The value used is the same as in java.util.GregorianCalendar
  313. public static final long ONE_YEAR = (long)(365.2425 * ONE_DAY);
  314. /** One century in milliseconds; convenient as a time-out value **/
  315. public static final long ONE_CENTURY = 100 * ONE_YEAR;
  316. }