Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: org/ematgine/utils/concurrent/Sync.java


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