Skip to content

Instantly share code, notes, and snippets.

@brianfromoregon
Created August 27, 2014 16:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianfromoregon/707ce3a94e45c933f126 to your computer and use it in GitHub Desktop.
Save brianfromoregon/707ce3a94e45c933f126 to your computer and use it in GitHub Desktop.
FileSystemLock
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