001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.eclipse.aether.named.support; 020 021import java.io.IOException; 022import java.io.UncheckedIOException; 023import java.nio.channels.FileChannel; 024import java.nio.channels.FileLock; 025import java.nio.channels.OverlappingFileLockException; 026import java.util.ArrayDeque; 027import java.util.Deque; 028import java.util.HashMap; 029import java.util.Map; 030import java.util.concurrent.TimeUnit; 031import java.util.concurrent.atomic.AtomicReference; 032import java.util.concurrent.locks.ReentrantLock; 033 034import org.eclipse.aether.named.NamedLockKey; 035 036import static org.eclipse.aether.named.support.Retry.retry; 037 038/** 039 * Named lock that uses {@link FileLock}. An instance of this class is about ONE LOCK (one file) 040 * and is possibly used by multiple threads. Each thread (if properly coded re boxing) will try to 041 * obtain either shared or exclusive lock. As file locks are JVM-scoped (so one JVM can obtain 042 * same file lock only once), the threads share file lock and synchronize according to it. Still, 043 * as file lock obtain operation does not block (or in other words, the method that does block 044 * cannot be controlled for how long it blocks), we are "simulating" thread blocking using 045 * {@link Retry} utility. 046 * This implementation performs coordination not only on thread (JVM-local) level, but also on 047 * process level, as long as other parties are using this same "advisory" locking mechanism. 048 * 049 * @since 1.7.3 050 */ 051public final class FileLockNamedLock extends NamedLockSupport { 052 private static final long RETRY_SLEEP_MILLIS = 100L; 053 054 private static final long LOCK_POSITION = 0L; 055 056 private static final long LOCK_SIZE = 1L; 057 058 /** 059 * Thread -> steps stack (true = shared, false = exclusive) 060 */ 061 private final Map<Thread, Deque<Boolean>> threadSteps; 062 063 /** 064 * The {@link FileChannel} this instance is about. 065 */ 066 private final FileChannel fileChannel; 067 068 /** 069 * The reference of {@link FileLock}, if obtained. 070 */ 071 private final AtomicReference<FileLock> fileLockRef; 072 073 /** 074 * Lock protecting "critical region": this is where threads are allowed to perform locking but should leave this 075 * region as quick as possible. 076 */ 077 private final ReentrantLock criticalRegion; 078 079 public FileLockNamedLock( 080 final NamedLockKey key, final FileChannel fileChannel, final NamedLockFactorySupport factory) { 081 super(key, factory); 082 this.threadSteps = new HashMap<>(); 083 this.fileChannel = fileChannel; 084 this.fileLockRef = new AtomicReference<>(null); 085 this.criticalRegion = new ReentrantLock(); 086 } 087 088 @Override 089 protected boolean doLockShared(final long time, final TimeUnit unit) throws InterruptedException { 090 boolean locked = retry(time, unit, RETRY_SLEEP_MILLIS, () -> doLockSharedPerform(time, unit), null, false); 091 if (!locked) { 092 forgetThreadWithoutSteps(); 093 } 094 return locked; 095 } 096 097 @Override 098 protected boolean doLockExclusively(final long time, final TimeUnit unit) throws InterruptedException { 099 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}