I want my application to check if another version of itself is already running.
For example, demo.jar
started, user clicks to run it again, but the second instance realizes "oh wait, there is already a demo.jar
running." and quits with a message.
Making an application single instance, can be achieved by using a mutex (Mutual Exclusion Semaphore). A Windows application loads the main form through the Application. Run( ) method. In the Main method, create a new mutex.
In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created.
If you want to check the work of java application, run 'ps' command with '-ef' options, that will show you not only the command, time and PID of all the running processes, but also the full listing, which contains necessary information about the file that is being executed and program parameters.
What you are looking for can probably best be accomplished with a lock file. By lock file I simply mean a file that will have a predefined location and whose existence is your mutex.
Test if that file exists when your program starts, if it does, exit immediately. Create a file in a known location. If your program exits normally, delete the lock file.
Probably best is if you can also populate the file with a pid (process id) so that you can detect abnormal exits that didn't delete the file but this get OS specific.
Java Code. Put this into a file called Main.java:
import java.net.*;
import java.io.*;
public class Main{
public static void main(String args[]){
ServerSocket socket = null;
try {
socket = new ServerSocket(34567);
System.out.println("Doing hard work for 100 seconds");
try{ Thread.sleep(100000); } catch(Exception e){ }
socket.close();
}
catch (IOException ex) {
System.out.println("App already running, exiting...");
}
finally {
if (socket != null)
try{ socket.close(); } catch(Exception e){}
}
}
}
Compile and run it
javac Main.java
java Main
Test it in a normal case:
Run the program. You have 100 seconds to run the program again in another terminal, it will fall through saying its already running. Then wait 100 seconds, it should allow you to run it in the 2nd terminal.
Test it after force halting the program with a kill -9
Conclusion:
The socket occupation is cleaned up by the operating system when your program is no longer operating. So you can be sure that the program will not run twice.
Drawbacks
If some sneaky person, or some naughty process were to bind all of the ports, or just your port, then your program will not run because it thinks its already running.
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