1 |
dl |
1.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 |
jsr166 |
1.3 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
dl |
1.1 |
*/ |
6 |
|
|
|
7 |
|
|
import java.util.*; |
8 |
|
|
import java.util.concurrent.*; |
9 |
|
|
import java.util.concurrent.locks.*; |
10 |
|
|
import java.util.concurrent.atomic.*; |
11 |
|
|
import java.io.*; |
12 |
|
|
|
13 |
|
|
/** |
14 |
jsr166 |
1.2 |
* A sample user extension of AbstractQueuedSynchronizer. |
15 |
dl |
1.1 |
*/ |
16 |
|
|
public final class Mutex extends AbstractQueuedSynchronizer implements Lock, java.io.Serializable { |
17 |
|
|
public boolean isHeldExclusively() { return getState() == 1; } |
18 |
jsr166 |
1.2 |
|
19 |
dl |
1.1 |
public boolean tryAcquire(int acquires) { |
20 |
|
|
return compareAndSetState(0, 1); |
21 |
|
|
} |
22 |
jsr166 |
1.2 |
|
23 |
dl |
1.1 |
public boolean tryRelease(int releases) { |
24 |
|
|
setState(0); |
25 |
|
|
return true; |
26 |
|
|
} |
27 |
|
|
public Condition newCondition() { return new ConditionObject(); } |
28 |
jsr166 |
1.2 |
|
29 |
dl |
1.1 |
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { |
30 |
|
|
s.defaultReadObject(); |
31 |
|
|
setState(0); // reset to unlocked state |
32 |
|
|
} |
33 |
|
|
|
34 |
jsr166 |
1.2 |
public void lock() { |
35 |
|
|
acquire(1); |
36 |
dl |
1.1 |
} |
37 |
jsr166 |
1.2 |
public boolean tryLock() { |
38 |
dl |
1.1 |
return tryAcquire(1); |
39 |
|
|
} |
40 |
jsr166 |
1.2 |
public void lockInterruptibly() throws InterruptedException { |
41 |
dl |
1.1 |
acquireInterruptibly(1); |
42 |
|
|
} |
43 |
|
|
public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { |
44 |
|
|
return tryAcquireNanos(1, unit.toNanos(timeout)); |
45 |
|
|
} |
46 |
|
|
public void unlock() { release(1); } |
47 |
|
|
} |