1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
*/ |
6 |
|
7 |
import java.io.ObjectInputStream; |
8 |
import java.io.IOException; |
9 |
import java.util.concurrent.*; |
10 |
import java.util.concurrent.locks.*; |
11 |
|
12 |
class Mutex implements Lock, java.io.Serializable { |
13 |
|
14 |
// Our internal helper class |
15 |
private static class Sync extends AbstractQueuedSynchronizer { |
16 |
// Report whether in locked state |
17 |
protected boolean isHeldExclusively() { |
18 |
return getState() == 1; |
19 |
} |
20 |
|
21 |
// Acquire the lock if state is zero |
22 |
public boolean tryAcquire(int acquires) { |
23 |
assert acquires == 1; // Otherwise unused |
24 |
return compareAndSetState(0, 1); |
25 |
} |
26 |
|
27 |
// Release the lock by setting state to zero |
28 |
protected boolean tryRelease(int releases) { |
29 |
assert releases == 1; // Otherwise unused |
30 |
if (getState() == 0) throw new IllegalMonitorStateException(); |
31 |
setState(0); |
32 |
return true; |
33 |
} |
34 |
|
35 |
// Provide a Condition |
36 |
Condition newCondition() { return new ConditionObject(); } |
37 |
|
38 |
// Deserialize properly |
39 |
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { |
40 |
s.defaultReadObject(); |
41 |
setState(0); // reset to unlocked state |
42 |
} |
43 |
} |
44 |
|
45 |
// The sync object does all the hard work. We just forward to it. |
46 |
private final Sync sync = new Sync(); |
47 |
|
48 |
public void lock() { sync.acquire(1); } |
49 |
public boolean tryLock() { return sync.tryAcquire(1); } |
50 |
public void unlock() { sync.release(1); } |
51 |
public Condition newCondition() { return sync.newCondition(); } |
52 |
public boolean isLocked() { return sync.isHeldExclusively(); } |
53 |
public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } |
54 |
public void lockInterruptibly() throws InterruptedException { |
55 |
sync.acquireInterruptibly(1); |
56 |
} |
57 |
public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { |
58 |
return sync.tryAcquireNanos(1, unit.toNanos(timeout)); |
59 |
} |
60 |
} |