Prevent launching multiple instances of a java application

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

    Creating a server socket, bounds to a specific port with a ServerSocket instance as the application starts is a straight way.
    Note that ServerSocket.accept() blocks, so running it in its own thread makes sense to not block the main Thread.

    Here is an example with a exception thrown as detected :

    public static void main(String[] args) {       
        assertNoOtherInstanceRunning();
        ...     // application code then        
    }
    
    public static void assertNoOtherInstanceRunning() {       
        new Thread(() -> {
            try {
                new ServerSocket(9000).accept();
            } catch (IOException e) {
              throw new RuntimeException("the application is probably already started", e);
            }
        }).start();       
    }
    

提交回复
热议问题