Prevent launching multiple instances of a java application

前端 未结 10 2126
你的背包
你的背包 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:47

    There are already available java methods in File class to achieve the same. The method is deleteOnExit() which ensure the file is automatically deleted when the JVM exits. However, it does not cater to forcible terminations. One should use FileLock in case of forcible termination.

    For more details check, https://docs.oracle.com/javase/7/docs/api/java/io/File.html

    Thus code snippet which could be used in the main method can be like :

    public static void main(String args[]) throws Exception {
    
        File f = new File("checkFile");
    
        if (!f.exists()) {
            f.createNewFile();
        } else {
            System.out.println("App already running" );
            return;
        }
    
        f.deleteOnExit();
    
        // whatever your app is supposed to do
        System.out.println("Blah Blah")
    }
    

提交回复
热议问题