How to make so that the java-application can be launched simultaneously in only one instance?
Somehow, I don’t want to look for the presence in the processes by a specific name, but the option to create / write to the file “marker” also does not work, because this option is not kresha-resistant (i.e., there should be an option that after the crash of the application it can start without throwing an error that it is already running).

    3 answers 3

    Look in the direction of the PID files. Write the PID of the process at the start, first checking for the presence of the PID file and pinging the process, sending SIG_DFL to it if the PID file exists. If the answer from SIG_DFL does not come, then the application has collapsed, and the PID-file remains, delete it and start the application ... In general, I wrote this way of demons ... Here, read the code here - pay attention to the getPID () function, like this remaking in Java is your concern :) For comparison, the same thing, but in Python , also look at get_pid ().

    • PIDs can be reused. If the application crashes and another process is created with the same PID, then the application will not start, although it should. (For example, if the crash system was restarted, but the file remained.) - AlexeyM
    • Well, after 2 years of using this approach, I have never had such a situation that another application was launched with the same PID. But even in this case, you can send some other signal and wait for a specific response from the application, but then you need to make a signal handler in it. Read about signals in general. - Shamanis

    Java Single Application Instance .

    • Um ... What if another application has already taken the selected port? - AlexeyM
    • It is possible to use a semaphore through JNI (it is interprocess). And look for analogue on linux platforms. - IronVbif

    You can do this:

    make the constructor private, and receive an instance in a static method in which it will be checked whether the object was created or not (If yes, then return the existing one, if not, create a new one)

    For example:

    public class Sngltn { private static Sngltn sngltn= null; private Sngltn(){ } public static Sngltn getSngltn(){ if (sngltn == null) sngltn = new Sngltn(); return sngltn; } public static void main(String[] args) { Sngltn mySngltn = Sngltn.getSngltn(); } 

    }

    • so what?) - Gorets
    • Mdja, a little confused task, but still, then you can add a check if there is already such an object in the system (in a static variable is not null) then exit the application. and all - zaitcbkru