I need to prevent users from starting my Java application (WebStart Swing app) multiple times. So if the application is already running it shouldn't be possible to start it again or show a warning / be closed again.
Is there some convenient way to achieve this? I thought about blocking a port or write sth to a file. But hopefully you can access some system properties or the JVM?
btw. target platform is Windows XP with Java 1.5
The best way of accomplishing this is using a named mutex. Create the mutex using code such as: bool firstInstance; Mutex mutex = new Mutex(false, "Local\\" + someUniqueName, out firstInstance); // If firstInstance is now true, we're the first instance of the application; // otherwise another instance is running.
In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time.
The command line arguments are stored in Eclipse in a Run Configuration (menu: Run > Run Configurations... , or Run > Debug Configurations... ). Just create two of them, reference the same main class, and specify different command line arguments, e.g. to specify different ports, then Run / Debug both of them.
I think your suggestion of opening a port to listen when you start your application is the best idea.
It's very easy to do and you don't need to worry about cleaning it up when you close your application. For example, if you write to a file but someone then kills the processes using Task Manager the file won't get deleted.
Also, if I remember correctly there is no easy way of getting the PID of a Java process from inside the JVM so don't try and formulate a solution using PIDs.
Something like this should do the trick:
private static final int PORT = 9999; private static ServerSocket socket; private static void checkIfRunning() { try { //Bind to localhost adapter with a zero connection queue socket = new ServerSocket(PORT,0,InetAddress.getByAddress(new byte[] {127,0,0,1})); } catch (BindException e) { System.err.println("Already running."); System.exit(1); } catch (IOException e) { System.err.println("Unexpected error."); e.printStackTrace(); System.exit(2); } }
This sample code explicitly binds to 127.0.0.1
which should avoid any firewall warnings, as any traffic on this address must be from the local system.
When picking a port try to avoid one mentioned in the list of Well Known Ports. You should ideally make the port used configurable in a file or via a command line switch in case of conflicts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With