Created
May 22, 2013 16:58
-
-
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
This file contains hidden or 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
| 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; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Originally found at http://www.rbgrn.net/content/43-java-single-application-instance#comment-1018