I only want one instance of my program running. But I want it to close the older ones, if they ore open.
This is in Java.
If the application is launched using Java Web Start it can access the SingleInstanceService of the JNLP API. Here is a demo. of the SIS.
You could always have a lock file, and make sure your program terminates if it can't acquire an exclusive lock on it.
Reference
I guess you're talking about a standalone java program, each instance running in its own JVM. In that case here are the options I see for you:
You can use a server socket address as an exclusive lock.
When your app starts, it will try to bind a server socket to a predefined address. If that fails, it means a previous instance of app is running and owning that address. Ping that address to tell the owner to exit.
serverSocket = new ServerSocket(localhost:8888)
if success,
start ServerSocketListeningThread
else
socket = new Socket(localhost:8888)
socket.close();
sleep(100);
repeat attempt of binding server socket
ServerSocketListeningThread
serverSocket.accept(); //block until someone connects
System.exit();
It's easy to shut down your app from command line
telnet localhost 8888
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