View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
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   * Named lock that uses {@link FileLock}. An instance of this class is about ONE LOCK (one file)
40   * and is possibly used by multiple threads. Each thread (if properly coded re boxing) will try to
41   * obtain either shared or exclusive lock. As file locks are JVM-scoped (so one JVM can obtain
42   * same file lock only once), the threads share file lock and synchronize according to it. Still,
43   * as file lock obtain operation does not block (or in other words, the method that does block
44   * cannot be controlled for how long it blocks), we are "simulating" thread blocking using
45   * {@link Retry} utility.
46   * This implementation performs coordination not only on thread (JVM-local) level, but also on
47   * process level, as long as other parties are using this same "advisory" locking mechanism.
48   *
49   * @since 1.7.3
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       * Thread -> steps stack (true = shared, false = exclusive)
60       */
61      private final Map<Thread, Deque<Boolean>> threadSteps;
62  
63      /**
64       * The {@link FileChannel} this instance is about.
65       */
66      private final FileChannel fileChannel;
67  
68      /**
69       * The reference of {@link FileLock}, if obtained.
70       */
71      private final AtomicReference<FileLock> fileLockRef;
72  
73      /**
74       * Lock protecting "critical region": this is where threads are allowed to perform locking but should leave this
75       * region as quick as possible.
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      * Drops the current thread's entry if it holds no step, so that the map does not retain threads that no longer
108      * use this lock.
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                         // if we own exclusive, that's still fine
133                         boolean weOwnExclusive = steps.contains(Boolean.FALSE);
134                         if (weOwnExclusive) {
135                             steps.push(Boolean.TRUE);
136                             return true;
137                         } else {
138                             // someone else owns exclusive, let's wait
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                         // if we own shared, that's attempted upgrade
165                         boolean weOwnShared = steps.contains(Boolean.TRUE);
166                         if (weOwnShared) {
167                             throw new LockUpgradeNotSupportedException(this); // Lock upgrade not supported
168                         } else {
169                             // someone else owns shared, let's wait
170                             return null;
171                         }
172                     } else {
173                         // if we own exclusive, that's fine
174                         boolean weOwnExclusive = steps.contains(Boolean.FALSE);
175                         if (weOwnExclusive) {
176                             steps.push(Boolean.FALSE);
177                             return true;
178                         } else {
179                             // someone else owns exclusive, let's wait
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      * Returns {@code true} if any other than this thread using this instance has any step recorded.
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      * Attempts to obtain real {@link FileLock}, returns non-null value is succeeds, or {@code null} if cannot.
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 }