How to make sure that only a single instance of a Java application is running?

前端 未结 11 1717
你的背包
你的背包 2020-12-09 20:23

I want my application to check if another version of itself is already running.

For example, demo.jar started, user clicks to run it again, but the sec

11条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 21:03

    What you are looking for can probably best be accomplished with a lock file. By lock file I simply mean a file that will have a predefined location and whose existence is your mutex.

    Test if that file exists when your program starts, if it does, exit immediately. Create a file in a known location. If your program exits normally, delete the lock file.

    Probably best is if you can also populate the file with a pid (process id) so that you can detect abnormal exits that didn't delete the file but this get OS specific.

提交回复
热议问题