开发者

Using an empty file to have one application instance

开发者 https://www.devze.com 2023-01-09 02:10 出处:网络
There\'s probably other ways of doing thi开发者_开发百科s but I\'d like to use an empty file to have one instance of an application running at a given time. This would be done by creating the file whe

There's probably other ways of doing thi开发者_开发百科s but I'd like to use an empty file to have one instance of an application running at a given time. This would be done by creating the file when the application is launched and have other application instances exit as soon as they detect the file.

The trouble with this approach is that the file can remain if the application stops unexpectedly and a ShutDownhook is proving unreliable.

How would you go about making this work as intended?


Bind to a high numbered port but don't listen. Two programs can't bind to the same TCP port on the same machine. Very cross-platform but still somewhat of a kludge.


Create the file and keep it open with an exclusive lock (that is, don't pass FILE_SHARE_READ, etc). When the second instance starts up, it tries to open the file and if it fails it means the first is still running.

If the first crashes, then Windows will automatically close all file handles and so the second process will come along, see that the file is there but since it can open it then it knows the first has crashed (this technique could also be used for a special dialog, "I see the previous instance of this application crashes, would you like to restore your last session?" or something)


You could always wrap your Java program in another program (doesn't need to be complicated - could even be a shell script) that would detect abnormal exit and delete the file. e.g.

if(!`java MyProgram`){
    rm lockFile
}


This may be a little much. But you can start a ServerSocket and bind to some arbitrary port that each application knows. If the port is available the application wins to start up, if not a binding exception is thrown and the application gracefully stops.


There is probably a better way to do this than using a file but with that approach you could write a timestamp to the file and update it at regular intervals using a Timer. Then when your program starts it could compare the timestamp in the file with the current time and quit if it is too close. This guarantees that your program will be able to restart no matter how it was terminated.


Assuming the lock will be released when the application exits and deleting the file on startup does the trick. See the link below.

http://jimlife.wordpress.com/2008/07/21/java-application-make-sure-only-singleone-instance-running-with-file-lock-ampampampampamp-shutdownhook/

P.S: I've tried using delete when the application exits but it seems to fail.

0

精彩评论

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