-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBooleanLock.java
More file actions
90 lines (68 loc) · 1.8 KB
/
Copy pathBooleanLock.java
File metadata and controls
90 lines (68 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package threadbook.ch17;
public class BooleanLock extends Object {
private boolean value;
public BooleanLock(boolean initialValue) {
value = initialValue;
}
public BooleanLock() {
this(false);
}
public synchronized void setValue(boolean newValue) {
if ( newValue != value ) {
value = newValue;
notifyAll();
}
}
public synchronized boolean waitToSetTrue(long msTimeout)
throws InterruptedException {
boolean success = waitUntilFalse(msTimeout);
if ( success ) {
setValue(true);
}
return success;
}
public synchronized boolean waitToSetFalse(long msTimeout)
throws InterruptedException {
boolean success = waitUntilTrue(msTimeout);
if ( success ) {
setValue(false);
}
return success;
}
public synchronized boolean isTrue() {
return value;
}
public synchronized boolean isFalse() {
return !value;
}
public synchronized boolean waitUntilTrue(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(true, msTimeout);
}
public synchronized boolean waitUntilFalse(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(false, msTimeout);
}
public synchronized boolean waitUntilStateIs(
boolean state,
long msTimeout
) throws InterruptedException {
if ( msTimeout == 0L ) {
while ( value != state ) {
wait(); // wait indefinitely until notified
}
// condition has finally been met
return true;
}
// only wait for the specified amount of time
long endTime = System.currentTimeMillis() + msTimeout;
long msRemaining = msTimeout;
while ( ( value != state ) && ( msRemaining > 0L ) ) {
wait(msRemaining);
msRemaining = endTime - System.currentTimeMillis();
}
// May have timed out, or may have met value,
// calculate return value.
return ( value == state );
}
}