1

我有一些代码来确保我的应用程序的单个实例正在运行,使用锁定文件:

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;
}

这在 99.9% 的时间里都有效。然后昨天,在生产中,该应用程序的第二个实例成功启动......

这段代码怎么会失败?

4

0 回答 0