Created
August 27, 2014 16:13
-
-
Save brianfromoregon/707ce3a94e45c933f126 to your computer and use it in GitHub Desktop.
FileSystemLock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.IOException; | |
import java.io.RandomAccessFile; | |
import java.nio.channels.FileLock; | |
import java.nio.channels.OverlappingFileLockException; | |
import static com.google.common.base.Preconditions.checkNotNull; | |
public class FileSystemLock { | |
private final File lockFile; | |
private RandomAccessFile writer; | |
private FileLock writeLock; | |
private boolean closed; | |
public FileSystemLock(File lockFile) { | |
this.lockFile = checkNotNull(lockFile); | |
} | |
public boolean tryLock() { | |
try { | |
writer = new RandomAccessFile(lockFile, "rw"); | |
writeLock = writer.getChannel().tryLock(Long.MAX_VALUE - 1, 1, false); | |
} catch (OverlappingFileLockException e) { | |
// Already locked by this JVM | |
return false; | |
} catch (Exception e) { | |
// TODO log e | |
return false; | |
} | |
if (writeLock == null) { | |
release(); | |
return false; | |
} else { | |
return true; | |
} | |
} | |
public void release() { | |
if (!closed) { | |
closed = true; | |
if (writeLock != null) { | |
try { | |
writeLock.release(); | |
} catch (IOException e) { | |
// TODO log e | |
} | |
} | |
if (writer != null) { | |
try { | |
writer.close(); | |
} catch (IOException e) { | |
// TODO log e | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment