开发者

Temporary file, single instance lock, and process kill (Java) [duplicate]

This question already has answers here: 开发者_开发问答 How to implement a single instance Java application? (17 answers) Closed 2 years ago.

I'm currently using a temp folder for my Java application to create a lock so that only one instance can be running at a time. This lock file MUST be deleted when the program exits.

This is fine, except for the case when the process is killed (not allowed to shutdown normally, e.g. from Windows Task Manager). If that happens, the user will never be able to run the program again... eek

Anyone have a suggestion? Is there a way to make the OS delete a folder on reboot or something similar? Should I find another way to have a "single instance lock?"

Also, the solution should be cross-platform if possible...


I think the lock file mentioned is a good way to go: - on application startup, check for the lock file - if it doesn't exist, create it and store the id of the process that creates the file inside that file - if it does exist, read the pid in the file and see if that process is still running - if not, replace the lock file and store your own process id inside - if the process is still running, return an error and quit

Use this(javasysmon) to get the PID as well as the running processes on the box

You should add a ShutDownHook in your main to cleanup the folder, that will catch a large percentage of the terminations.

For more reliable hooking of the JVM look at this paper:
http://www.ibm.com/developerworks/java/library/i-signalhandling/


When the app starts, check for the lock file, and if it exists print an error saying something along the lines: "Either there is another instance running, or you have a stale lock. If there is no other instance running, delete xyz.lock and restart".

A better solution might be to bind to a fixed (and non-standard) TCP port. If you cannot bind to it, assume that there is another instance of your process running.

Third, and probably the best way is to use java.nio.channels.FileLock to take an exclusive lock on a file.


You could look into File.deleteOnExit(). It makes the JVM delete the file when it exits. It can't be undone.

But like the other answers, you'll need to check if it exists when you start up.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜