ekartoyev
2/18/2019 - 4:16 PM

Java - locking a file to ensure one single instance is running

Also survives Garbage Collection. The lock is released once your process ends, doesn't matter if regular exit or crash or whatever.

String userHome = System.getProperty("user.home");
File file = new File(userHome, "my.lock");
try {
    FileChannel fc = FileChannel.open(file.toPath(),
            StandardOpenOption.CREATE,
            StandardOpenOption.WRITE);
    FileLock lock = fc.tryLock();
    if (lock == null) {
        System.out.println("another instance is running");
    }
} catch (IOException e) {
    throw new Error(e);
}