Prevent launching multiple instances of a java application

前端 未结 10 2128
你的背包
你的背包 2020-12-03 03:19

I want to prevent the user from running my java application multiple times in parallel.

To prevent this, I have created a lock file when am opening the application,

10条回答
  •  借酒劲吻你
    2020-12-03 03:29

    You could use a FileLock, this also works in environments where multiple users share ports:

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

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

提交回复
热议问题