I have some code to ensure a single instance of my app is running, using a lock file:
public static boolean ensureSingleInstance(String appName) {
try {
String path = Paths.get(System.getProperty("java.io.tmpdir"), appName + ".lock").toString();
File file = new File(path);
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
if (randomAccessFile.getChannel().tryLock() != null) {
file.deleteOnExit();
return true;
}
} catch (IOException ignore) {
}
return false;
}
This works 99.9% of the time. And then yesterday, in production, a second instance of the app successfully started...
How can this code fail?