-
Notifications
You must be signed in to change notification settings - Fork 5
/
Access.java
79 lines (71 loc) · 2.05 KB
/
Access.java
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
package com.teragrep.rlp_03.context.frame.access;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
public final class Access implements Supplier<Lease> {
private long accessCount;
private boolean terminated;
private final Lock lock;
public Access() {
this.accessCount = 0; // TODO consider using a semaphore
this.terminated = false;
this.lock = new ReentrantLock();
}
@Override
public Lease get() {
lock.lock();
try {
if (terminated()) {
throw new IllegalStateException("Access already terminated");
}
accessCount++;
return new Lease(this);
} finally {
lock.unlock();
}
}
public void terminate() {
if (lock.tryLock()) {
try {
if (accessCount != 0) {
throw new IllegalStateException("Open leases still exist");
} else {
if (terminated) {
throw new IllegalStateException("Access already terminated");
}
terminated = true;
}
} finally {
lock.unlock();
}
}
else {
throw new IllegalStateException("Lease operation in progress");
}
}
public boolean terminated() {
lock.lock();
try {
return terminated;
}
finally {
lock.unlock();
}
}
public void release(Lease lease) {
if (lease.isOpen()) {
throw new IllegalStateException("Can not be release an open lease");
}
lock.lock();
try {
long newAccessCount = accessCount - 1;
if (newAccessCount < 0) {
throw new IllegalStateException("AccessCount must not be negative");
}
accessCount = newAccessCount;
}
finally {
lock.unlock();
}
}
}