Skip to content

Instantly share code, notes, and snippets.

@CaptinKraken
Created May 22, 2013 16:58
Show Gist options
  • Save CaptinKraken/5629138 to your computer and use it in GitHub Desktop.
Save CaptinKraken/5629138 to your computer and use it in GitHub Desktop.
Java Single Instance Lock. Creates a simple and reliable lock file that is cross platform JavaFX, Java
private static boolean lockInstance(final String lockFile) {
try {
final File file = new File(lockFile);
final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
final FileLock fileLock = randomAccessFile.getChannel().tryLock();
if (fileLock != null) {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
fileLock.release();
randomAccessFile.close();
file.delete();
} catch (Exception e) {
log.error("Unable to remove lock file: " + lockFile, e);
}
}
});
return true;
}
} catch (Exception e) {
log.error("Unable to create and/or lock file: " + lockFile, e);
}
return false;
}
@CaptinKraken
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment