001package co.codewizards.cloudstore.core.io; 002 003import static java.util.Objects.*; 004 005import java.io.IOException; 006import java.util.HashMap; 007import java.util.Map; 008 009import org.slf4j.Logger; 010import org.slf4j.LoggerFactory; 011 012import co.codewizards.cloudstore.core.oio.File; 013 014/** 015 * Factory creating {@link LockFile} instances. 016 * <p> 017 * All methods of this class are thread-safe. 018 * @author Marco หงุ่ยตระกูล-Schulze - marco at codewizards dot co 019 */ 020public class LockFileFactory { 021 022 private static final Logger logger = LoggerFactory.getLogger(LockFileFactory.class); 023 024 private static class LockFileFactoryHolder { 025 public static final LockFileFactory instance = new LockFileFactory(); 026 } 027 028 private final Object mutex = this; 029 030 protected LockFileFactory() { } 031 032 public static LockFileFactory getInstance() { 033 return LockFileFactoryHolder.instance; 034 } 035 036 private final Map<File, LockFileImpl> file2LockFileImpl = new HashMap<File, LockFileImpl>(); 037 038 /** 039 * Acquire an exclusive lock on the specified file. 040 * <p> 041 * <b>Important:</b> You <i>must</i> invoke {@link LockFile#release()} on the returned object! Use a try-finally-block 042 * to ensure it: 043 * <pre> LockFile lockFile = LockFileFactory.getInstance().acquire(theFile, theTimeout); 044 * try { 045 * // do something 046 * } finally { 047 * lockFile.release(); 048 * }</pre> 049 * <p> 050 * Since Java 7, it is alternatively possible to use the try-with-resources clause like this: 051 * <pre> try ( LockFile lockFile = LockFileFactory.getInstance().acquire(theFile, theTimeout); ) { 052 * // do something while the file represented by 'lockFile' is locked. 053 * }</pre> 054 * <p> 055 * If the JVM is interrupted or shut down before {@code release()}, the file-lock is released by the 056 * operating system, but a missing {@code release()} causes the file to be locked for the entire remaining runtime 057 * of the JVM! This problem does not exist using the new try-with-resources-clause (since Java 7). 058 * <p> 059 * <b>Important:</b> This is <i>not</i> usable for the synchronization of multiple threads within the same Java virtual machine! 060 * Multiple {@link LockFile}s on the same {@link File} are possible within the same JVM! This locking mechanism 061 * only locks against separate processes! Since this implementation is based on {@link java.nio.channels.FileLock FileLock}, 062 * please consult its Javadoc for further information. 063 * <p> 064 * To make it possible to synchronise multiple threads in the same JVM, too, there's {@link LockFile#getLock()}. 065 * <p> 066 * Multiple invocations of this method on the same given {@code file} return multiple different {@code LockFile} instances. 067 * The actual lock is held until the last {@code LockFile} instance was {@linkplain LockFile#release() released}. 068 * <p> 069 * This method is thread-safe. 070 * @param file the file to be locked. Must not be <code>null</code>. If this file does not exist in the file system, 071 * it is created by this method. 072 * @param timeoutMillis the timeout to wait for the lock to be acquired in milliseconds. The value 0 means to 073 * wait forever. 074 * @return the {@code LockFile}. Never <code>null</code>. This <i>must</i> be 075 * {@linkplain java.nio.channels.FileLock#release() released} 076 * (use a try-finally-block)! 077 * @throws TimeoutException if the {@code LockFile} could not be acquired within the timeout specified by {@code timeoutMillis}. 078 * @see LockFile#release() 079 */ 080 public LockFile acquire(File file, final long timeoutMillis) throws TimeoutException { 081 requireNonNull(file, "file"); 082 try { 083 file = file.getCanonicalFile(); 084 } catch (final IOException e) { 085 throw new RuntimeException(e); 086 } 087 088 LockFileImpl lockFileImpl; 089 synchronized (mutex) { 090 lockFileImpl = file2LockFileImpl.get(file); 091 if (lockFileImpl == null) { 092 lockFileImpl = new LockFileImpl(this, file); 093 file2LockFileImpl.put(file, lockFileImpl); 094 logger.trace("acquire: Adding file='{}' lockFileImpl={}", file, lockFileImpl); 095 } 096 ++lockFileImpl.acquireRunningCounter; 097 } 098 boolean exceptionThrown = true; 099 try { 100 // The following must NOT be synchronised! Otherwise we might wait here longer than the current timeout 101 // (as long as the longest timeout of all acquire methods running concurrently). 102 lockFileImpl.acquire(timeoutMillis); 103 exceptionThrown = false; 104 } finally { 105 synchronized (mutex) { 106 final int lockCounter = lockFileImpl.getLockCounter(); 107 final int acquireRunningCounter = --lockFileImpl.acquireRunningCounter; 108 109 if (lockCounter < 1 && acquireRunningCounter < 1) { 110 logger.trace("acquire: Removing lockFileImpl={}", lockFileImpl); 111 final LockFileImpl removed = file2LockFileImpl.remove(file); 112 if (removed != lockFileImpl) 113 throw new IllegalStateException(String.format("file2LockFileImpl.remove(file) != lockFileImpl :: %s != %s", removed, lockFileImpl)); 114 } 115 116 if (lockCounter < 1 && ! exceptionThrown) 117 throw new IllegalStateException("lockCounter < 1, but no exception thrown!"); 118 } 119 } 120 return new LockFileProxy(lockFileImpl); 121 } 122 123 /** 124 * Callback from {@link LockFileImpl#release()}. 125 * @param lockFileImpl the {@code LockFileImpl} which notifies this factory about being released. 126 */ 127 protected void postRelease(final LockFileImpl lockFileImpl) { 128 synchronized (mutex) { 129 final LockFileImpl lockFileImpl2 = file2LockFileImpl.get(lockFileImpl.getFile()); 130 if (lockFileImpl != lockFileImpl2) 131 throw new IllegalArgumentException(String.format("Unknown lockFileImpl instance (not managed by this registry)! file2LockFileImpl.get(lockFileImpl.getFile()) != lockFileImpl :: %s != %s ", lockFileImpl2, lockFileImpl)); 132 133 final int lockCounter = lockFileImpl.getLockCounter(); 134 final int acquireRunningCounter = lockFileImpl.acquireRunningCounter; 135 136 if (lockCounter < 1 && acquireRunningCounter < 1) { 137 logger.trace("postRelease: Removing lockFileImpl={}", lockFileImpl); 138 final LockFileImpl removed = file2LockFileImpl.remove(lockFileImpl.getFile()); 139 if (removed != lockFileImpl) 140 throw new IllegalStateException(String.format("file2LockFileImpl.remove(file) != lockFileImpl :: %s != %s", removed, lockFileImpl)); 141 } 142 } 143 } 144 145}