views:

61

answers:

6

There's probably other ways of doing this 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?

+1  A: 

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)

Dean Harding
This may not be a cross platform solution. See: http://www.devx.com/Java/Article/7870
Russ Hayward
+1  A: 

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
}
Scott
+2  A: 

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.

bowenl2
Very clever. I'll have to remember that trick.
Chris Kessel
+1  A: 

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.

John V.
+1  A: 

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.

Russ Hayward
A: 

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.

James P.