Answer the question
In order to leave comments, you need to log in
How to prevent multiple instances of a program from running?
Hello, I wrote a program, compiled it into a jar file. But this application can run in multiple instances, how can I disable this?
Thank you very much in advance!
Answer the question
In order to leave comments, you need to log in
How to....search..
stackoverflow.com/questions/920386/how-to-allow-en...
stackoverflow.com/questions/177189/how-to-implemen...
Use a hidden file as a lock: when you start the program, look if the file exists, round off and exit, otherwise create the file and continue. Only there are 2 points:
1. If 2 instances of the program were launched almost simultaneously, both may not find the file and try to create it, so it's better to check this case:
File file = new File("<your_path_here>");
if (!file.createNewFile) {
System.out.pprintln("The instance is already running");
return;
}
I'm taking an approach that has the indirect effect of blocking concurrently running applications.
1. In the settings file, store the number of a network free port, for example 5555
2. When starting the program, raise the ServerSocket and listen to this port on localhost
I use this trick to properly terminate an already running program by starting it again with the STOP parameter. In this case, the running program sends a termination command to localhost:5555. What is read through the ServerSocket and the program exits gracefully.
A side effect of this approach is that running a second instance of the program (without the STOP parameter) will fail, as it will try to open a ServerSocket on the same port (5555).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question