KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > EDU > oswego > cs > dl > util > concurrent > TimeoutSync


1 /*
2   File: TimeoutSync.java
3
4   Originally written by Doug Lea and released into the public domain.
5   This may be used for any purposes whatsoever without acknowledgment.
6   Thanks for the assistance and support of Sun Microsystems Labs,
7   and everyone contributing, testing, and using this code.
8
9   History:
10   Date Who What
11    1Aug1998 dl Create public version
12 */

13
14 package EDU.oswego.cs.dl.util.concurrent;
15
16 /**
17  * A TimeoutSync is an adaptor class that transforms all
18  * calls to acquire to instead invoke attempt with a predetermined
19  * timeout value.
20  *<p>
21  * <b>Sample Usage</b>. A TimeoutSync can be used to obtain
22  * Timeouts for locks used in SyncCollections. For example:
23  * <pre>
24  * Mutex lock = new Mutex();
25  * TimeoutSync timedLock = new TimeoutSync(lock, 1000); // 1 sec timeouts
26  * Set set = new SyncSet(new HashSet(), timedlock);
27  * try {
28  * set. add("hi");
29  * }
30  * // SyncSets translate timeouts and other lock failures
31  * // to unsupported operation exceptions,
32  * catch (UnsupportedOperationException ex) {
33  * System.out.println("Lock failure");
34  * }
35  * </pre>
36  *
37  * <p>[<a HREF="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
38  * @see Sync
39 **/

40
41
42 public class TimeoutSync implements Sync {
43
44   protected final Sync sync_; // the adapted sync
45
protected final long timeout_; // timeout value
46

47   /**
48    * Create a TimeoutSync using the given Sync object, and
49    * using the given timeout value for all calls to acquire.
50    **/

51
52   public TimeoutSync(Sync sync, long timeout) {
53     sync_ = sync;
54     timeout_ = timeout;
55   }
56
57   public void acquire() throws InterruptedException JavaDoc {
58     if (!sync_.attempt(timeout_)) throw new TimeoutException(timeout_);
59   }
60
61   public boolean attempt(long msecs) throws InterruptedException JavaDoc {
62     return sync_.attempt(msecs);
63   }
64
65   public void release() {
66     sync_.release();
67   }
68
69 }
70
Popular Tags