ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/loops/Mutex.java
Revision: 1.1
Committed: Fri Apr 9 20:12:06 2004 UTC (20 years, 2 months ago) by jsr166
Branch: MAIN
Log Message:
Add ALoops benchmark to src/loops, target 'loops' already in build.xml

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     class Mutex implements Lock, java.io.Serializable {
7    
8     // Our internal helper class
9     private static class Sync extends AbstractQueuedSynchronizer {
10     // 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     }
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     sync.acquireInterruptibly(1);
50     }
51     public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
52     return sync.tryAcquireNanos(1, unit.toNanos(timeout));
53     }
54     }