Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Advanced
Feb 4, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Limit Your App To One Instance

How can we make sure that only one instance of our Java application is running on a machine? Java does not provide the means of finding out if another instance of our app is running. And, sometimes, we may really want to limit the user of our app to only one running instance. So, what do we do?

One way of dealing with this problem is to have our app create a file under a certain file name when it runs for the first time. Subsequent launches of our app will check for that file. If it already exists, the app knows another instance is already running and will inform the user, then quit. The first instance of the app, however has to delete the file before it exits.

The drawback of this approach is that out first instance of the app may crash, or may be killed by the user, or for whatever reason, it may cease to exist without having a chance to remove the little file that indicates a running instance.

Another way of dealing with this problem is via the use of java.net.ServerSocket class. The idea is to have an instance of ServerSocket listening over some port for as long as the first running instance of our app runs. Consequent launches of our app will try to set up their own ServerSocket over the same port, and will get a java.net.BindException (because we cannot start two versions of a server on the same port), and we'll know that another instance of the app is already running.

Now, if, for any unintentional reason, our app dies, the resources used by the app die away with it, and another instance can start and set the ServerSocket to prevent more instances from running. The following illustrates our approach:

private static final int RUN_PORT = 9666; 
//use an obscure port 

void main(String[] av) 
                java.net.ServerSocket ss = new java.net.ServerSocket(PORT); 
      catch (java.net.BindException ex) 
                System.out.println("Program already running"); 
      catch (java.io.IOException ex) 
        //the rest of your code for the main(...) method 
Behrouz Fallahi
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date