ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/loops/Mutex.java
Revision: 1.2
Committed: Thu Apr 14 23:16:10 2011 UTC (13 years, 2 months ago) by jsr166
Branch: MAIN
CVS Tags: release-1_7_0
Changes since 1.1: +31 -31 lines
Log Message:
whitespace

File Contents

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