且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

防止jar的多个实例运行

更新时间:2023-11-22 21:26:52

只是为了确保我了解您想要的,您想要一个在后台运行的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.