Java – Single Application Instance

Duke, the Java Mascot, in the waving pose. Duk...

Image via Wikipedia

If you want to prevent the user from running multiple copies of your Java application here are two approaches I could suggest you:
1) You can verify if a busy file exist. If one exists, abort. If not create one.  The process to test and create the file can be developed in the script file that triggers the application or in the application itself.  When the app exists it deletes the busy marker file. The main problem with this simple approach is if your app crashes, it won’t delete the busy file. You have to manually delete it before you can run the app again.

2) Another approach is to have your application open a ServerSocket on a particular port number. The OS will prevent other processes from opening a ServerSocket that uses the same port. If you start the application and are unable to open your ServerSocket (i.e. if you get an “address already in use” exception) assume that the application is already running. In that case, you can use a Socket to connect to the running application and pass it whatever commands you like, or just abort.

Source: http://mindprod.com/jgloss/singleinstance.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: