check for single instance java program

Launch the application using Java Web Start and implement the SingleInstanceService of the JNLP API. Here is a demo. of the SingleInstanceService.

If it attempted to open another instance of the program I would like the current instance to be brought to the foreground.

Hook that up in the newActivation(String[]) method of the SingleInstanceListener. It will be passed any arguments that were provided for the new launch. The existing instance gets to decide what to do with the new args (e.g. change file, add new tab, ignore..)


You can do it using a ShutDownHook and a lock file , see this simple example .

I think that it is the simplest way ...


There is no prev-instance in Java, but you can create a pid file in the temp (or /var/run) directory. (And make it File.deleteOnExit() to clean it anyway on exit)

To bring the existing window to top, you may notify the program yourself, thru named pipe, unix socket, or java remote method call, etc. A simple & dirty way is to write to a small file, say $TEMP/foobar-app.bring-to-top, and the program should periodically poll this small file, if it comes to exist, bring the window to top and remove this small file.

I guess Java couldn't handle signals, i.e., kill -HUP PID may not work for Java applications. Even if it could, not every OS have signals.

Tags:

Java

Swing