01: /*
02: File: TimeoutSync.java
03:
04: Originally written by Doug Lea and released into the public domain.
05: This may be used for any purposes whatsoever without acknowledgment.
06: Thanks for the assistance and support of Sun Microsystems Labs,
07: and everyone contributing, testing, and using this code.
08:
09: 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: public class TimeoutSync implements Sync {
42:
43: protected final Sync sync_; // the adapted sync
44: protected final long timeout_; // timeout value
45:
46: /**
47: * Create a TimeoutSync using the given Sync object, and
48: * using the given timeout value for all calls to acquire.
49: **/
50:
51: public TimeoutSync(Sync sync, long timeout) {
52: sync_ = sync;
53: timeout_ = timeout;
54: }
55:
56: public void acquire() throws InterruptedException {
57: if (!sync_.attempt(timeout_))
58: throw new TimeoutException(timeout_);
59: }
60:
61: public boolean attempt(long msecs) throws InterruptedException {
62: return sync_.attempt(msecs);
63: }
64:
65: public void release() {
66: sync_.release();
67: }
68:
69: }
|