esuslogo
 [To advertise Java(tm) Events here, contact joris@esus.com!]
banner

Java™
by example!






New @ Esus.com


  gb  In-house search engine for better results!

  gb  Get updates with the esus.com
newsletter!









  Home 
 Browse Categories 
 Ask a Java Question 
 Help 
  For Java Tips & Tricks, subscribe to the esus.com newsletter!
Search Java Q&A, Links, API's:   adv 

How do I check if another instance of the same program is already running?
The best way in my opinion is to use ServerSockets. A ServerSocket can only be opened once. So if the application is already running, the creation of the same ServerSocket will fail. This is how you know the app is already running. Sockets are the best approach because the ports get closed by the JVM upon shut down, locking files used for behavior might not work under all circumstances.
Here is a sample:

 
public class MainApp
{
private static ServerSocket applLockSocket;

public MainApp()
{
// Do something...

}

private static boolean isApplRunning()
{
try
{
// Open a ServerSocket on an app specific port
applLockSocket = new ServerSocket(2345);
}
catch (java.net.BindException e)
{
//There is already an application running!
return true;
}
catch (IOException e)
{
// This was not expected...
}
return false;
}

public static void main(String[] args)
{
try
{
if (isApplRunning())
{
// Since we only allow this application to be
// started once, we need to show the user, that
// this app is already running...
JOptionPane.showMessageDialog(null
,"This app is already running!"
,"Info:"
,JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}

// Start the application...
new MainApp();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null
,e.toString()
,"Error:"
,JOptionPane.ERROR_MESSAGE);
}
}
}




Further Information
Author of answer:

Comments to this answer are only viewable by members. Login or become a member!





Terms of Service | Privacy Policy | Contact

Copyright © 2000-2003 Esus.com - All Rights Reserved 
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. Esus.com is independent of Sun Microsystems, Inc. All other trademarks are the sole property of their respective owners.