防止jar的多个实例运行 [英] Prevent multiple instance of jar running

查看:85
本文介绍了防止jar的多个实例运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的中间层jar文件在linux服务器上运行.我希望该jar文件在后台不间断运行.

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 &

但是当我重新运行此命令时,将创建并运行jar的另一个新实例.

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

我已经搜索过Google.他们提出了一些选择. 绑定ServerSocket".但这对我不起作用.按Enter或Ctrl + C后进程被杀死.

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.

我想从罐子中获得两个好处.一个总是以失败告终.如果使用相同命令重新启动jar,则使用另一个命令(nohup java -jar RushMiddleLayer.jar&). 它应该替换现有的jar,而不是创建新的实例.

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.

推荐答案

只是为了确保我了解您想要的,您想要一个在后台运行的jar文件,并且只能一次启动一次?

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. 使用端口作为信号灯(按照您的建议)
  2. 使用文件作为信号量.

对于选项1,

代码应该像这样简单:

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

将抛出 IOException ,如果无法在此端口上打开服务器套接字.但是,如果某些其他应用程序正在使用此端口,也会发生这种情况.因此请小心选择哪个端口号.

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.

对于选项2, 您只需使用 FileWriter 并创建一个虚拟对象文件并保持打开状态,直到jar/程序完成(或关闭).当第二个jar实例尝试打开时,将引发异常,并且将无法启动,因为它会尝试打开要写入的文件,这会产生IOException,因为只有一个进程可以拥有一个IOException.同时将句柄写入文件.

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.

这篇关于防止jar的多个实例运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆