1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.aether.named.support;
20
21 import java.io.IOException;
22 import java.io.UncheckedIOException;
23 import java.nio.channels.FileChannel;
24 import java.nio.channels.FileLock;
25 import java.nio.channels.OverlappingFileLockException;
26 import java.util.ArrayDeque;
27 import java.util.Deque;
28 import java.util.HashMap;
29 import java.util.Map;
30 import java.util.concurrent.TimeUnit;
31 import java.util.concurrent.atomic.AtomicReference;
32 import java.util.concurrent.locks.ReentrantLock;
33
34 import org.eclipse.aether.named.NamedLockKey;
35
36 import static org.eclipse.aether.named.support.Retry.retry;
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51 public final class FileLockNamedLock extends NamedLockSupport {
52 private static final long RETRY_SLEEP_MILLIS = 100L;
53
54 private static final long LOCK_POSITION = 0L;
55
56 private static final long LOCK_SIZE = 1L;
57
58
59
60
61 private final Map<Thread, Deque<Boolean>> threadSteps;
62
63
64
65
66 private final FileChannel fileChannel;
67
68
69
70
71 private final AtomicReference<FileLock> fileLockRef;
72
73
74
75
76
77 private final ReentrantLock criticalRegion;
78
79 public FileLockNamedLock(
80 final NamedLockKey key, final FileChannel fileChannel, final NamedLockFactorySupport factory) {
81 super(key, factory);
82 this.threadSteps = new HashMap<>();
83 this.fileChannel = fileChannel;
84 this.fileLockRef = new AtomicReference<>(null);
85 this.criticalRegion = new ReentrantLock();
86 }
87
88 @Override
89 protected boolean doLockShared(final long time, final TimeUnit unit) throws InterruptedException {
90 boolean locked = retry(time, unit, RETRY_SLEEP_MILLIS, () -> doLockSharedPerform(time, unit), null, false);
91 if (!locked) {
92 forgetThreadWithoutSteps();
93 }
94 return locked;
95 }
96
97 @Override
98 protected boolean doLockExclusively(final long time, final TimeUnit unit) throws InterruptedException {
99 boolean locked = retry(time, unit, RETRY_SLEEP_MILLIS, () -> doLockExclusivelyPerform(time, unit), null, false);
100 if (!locked) {
101 forgetThreadWithoutSteps();
102 }
103 return locked;
104 }
105
106
107
108
109
110 private void forgetThreadWithoutSteps() {
111 criticalRegion.lock();
112 try {
113 Deque<Boolean> steps = threadSteps.get(Thread.currentThread());
114 if (steps != null && steps.isEmpty()) {
115 threadSteps.remove(Thread.currentThread());
116 }
117 } finally {
118 criticalRegion.unlock();
119 }
120 }
121
122 private Boolean doLockSharedPerform(final long time, final TimeUnit unit) throws InterruptedException {
123 if (criticalRegion.tryLock(time, unit)) {
124 try {
125 Deque<Boolean> steps = threadSteps.computeIfAbsent(Thread.currentThread(), k -> new ArrayDeque<>());
126 FileLock obtainedLock = fileLockRef.get();
127 if (obtainedLock != null) {
128 if (obtainedLock.isShared()) {
129 steps.push(Boolean.TRUE);
130 return true;
131 } else {
132
133 boolean weOwnExclusive = steps.contains(Boolean.FALSE);
134 if (weOwnExclusive) {
135 steps.push(Boolean.TRUE);
136 return true;
137 } else {
138
139 return null;
140 }
141 }
142 }
143
144 FileLock fileLock = obtainFileLock(true);
145 if (fileLock != null) {
146 fileLockRef.set(fileLock);
147 steps.push(Boolean.TRUE);
148 return true;
149 }
150 } finally {
151 criticalRegion.unlock();
152 }
153 }
154 return null;
155 }
156
157 private Boolean doLockExclusivelyPerform(final long time, final TimeUnit unit) throws InterruptedException {
158 if (criticalRegion.tryLock(time, unit)) {
159 try {
160 Deque<Boolean> steps = threadSteps.computeIfAbsent(Thread.currentThread(), k -> new ArrayDeque<>());
161 FileLock obtainedLock = fileLockRef.get();
162 if (obtainedLock != null) {
163 if (obtainedLock.isShared()) {
164
165 boolean weOwnShared = steps.contains(Boolean.TRUE);
166 if (weOwnShared) {
167 throw new LockUpgradeNotSupportedException(this);
168 } else {
169
170 return null;
171 }
172 } else {
173
174 boolean weOwnExclusive = steps.contains(Boolean.FALSE);
175 if (weOwnExclusive) {
176 steps.push(Boolean.FALSE);
177 return true;
178 } else {
179
180 return null;
181 }
182 }
183 }
184
185 FileLock fileLock = obtainFileLock(false);
186 if (fileLock != null) {
187 fileLockRef.set(fileLock);
188 steps.push(Boolean.FALSE);
189 return true;
190 }
191 } finally {
192 criticalRegion.unlock();
193 }
194 }
195 return null;
196 }
197
198 @Override
199 protected void doUnlock() {
200 criticalRegion.lock();
201 try {
202 Deque<Boolean> steps = threadSteps.computeIfAbsent(Thread.currentThread(), k -> new ArrayDeque<>());
203 if (steps.isEmpty()) {
204 throw new IllegalStateException("Wrong API usage: unlock without lock");
205 }
206 steps.pop();
207 if (steps.isEmpty()) {
208 threadSteps.remove(Thread.currentThread());
209 if (!anyOtherThreadHasSteps()) {
210 try {
211 fileLockRef.getAndSet(null).release();
212 } catch (IOException e) {
213 throw new UncheckedIOException(e);
214 }
215 }
216 }
217 } finally {
218 criticalRegion.unlock();
219 }
220 }
221
222
223
224
225 private boolean anyOtherThreadHasSteps() {
226 return threadSteps.entrySet().stream()
227 .filter(e -> !Thread.currentThread().equals(e.getKey()))
228 .map(Map.Entry::getValue)
229 .anyMatch(d -> !d.isEmpty());
230 }
231
232
233
234
235 private FileLock obtainFileLock(final boolean shared) {
236 FileLock result;
237 try {
238 result = fileChannel.tryLock(LOCK_POSITION, LOCK_SIZE, shared);
239 } catch (OverlappingFileLockException e) {
240 logger.trace("File lock overlap on '{}'", key(), e);
241 return null;
242 } catch (IOException e) {
243 logger.trace("Failure on acquire of file lock for '{}'", key(), e);
244 throw new UncheckedIOException("Failed to acquire lock file channel for '" + key() + "'", e);
245 }
246 return result;
247 }
248 }