Prevent multiple instance of jar running

Issue

I have my middle layer jar file running on the linux server. I want that jar file running in background non-stop.

nohup java -jar RushMiddleLayer.jar &

But when i re-run this command, another new instance of the jar created and running.

I have searched through google. They suggested some options.
“Bind a ServerSocket”. But which is not working for me. Process killed after press enter or Ctrl+C.

I want to have two benefits from the jar. One is always running with fail. Another if restart the jar using the same command (nohup java -jar RushMiddleLayer.jar &).
It should replace the existing jar, not create the new instance.

Solution

Just to make sure I understand what you want, you want a jar file that runs in the background and it is only able to be launched once and once only?

If this is what you want, there is two ways to achieve this:

  1. Use a port as a semaphore (as you suggested)
  2. Use a file as a semaphore.

For option 1,

The code should be as simple as something like:

try {
    serverSocket = new ServerSocket(port);
} catch (IOException e) {
    System.out.println("Could not listen on port: " + port);
    // ...
}

An IOException will be thrown, if you cannot open server socket on this port. However, this could also occur if some other application is using this port. So be careful what port number you choose.

For option 2,
You simply use a FileWriter and create a dummy file and keep this file open until the jar/program is finished (or closed). When a second instance of the jar attempts to open, an exception will be thrown and it won’t be able to start due to the fact that it will try to open the file for writing which produces an IOException because only one process can have a write handle to a file at the same time.

Answered By – Jamie Reid

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published