Prevent multiple instance of jar running

我们两清 提交于 2021-01-28 00:48:18

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28642972/prevent-multiple-instance-of-jar-running

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!