如何允许一次只运行一个 Java 程序实例? [英] How to allow running only one instance of a Java program at a time?

查看:39
本文介绍了如何允许一次只运行一个 Java 程序实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要防止用户多次启动我的 Java 应用程序(WebStart Swing 应用程序).因此,如果应用程序已经在运行,则不应再次启动它或显示警告/再次关闭.

I need to prevent users from starting my Java application (WebStart Swing app) multiple times. So if the application is already running it shouldn't be possible to start it again or show a warning / be closed again.

有什么方便的方法可以实现这一点吗?我想过阻塞端口或将某事写入文件.但希望您可以访问某些系统属性或 JVM?

Is there some convenient way to achieve this? I thought about blocking a port or write sth to a file. But hopefully you can access some system properties or the JVM?

顺便说一句.目标平台是带有 Java 1.5 的 Windows XP

btw. target platform is Windows XP with Java 1.5

推荐答案

我认为您建议在启动应用程序时打开一个端口进行侦听是最好的主意.

I think your suggestion of opening a port to listen when you start your application is the best idea.

这很容易做到,而且您在关闭应用程序时无需担心清理它.例如,如果您写入文件,但随后有人使用任务管理器终止了进程,则该文件不会被删除.

It's very easy to do and you don't need to worry about cleaning it up when you close your application. For example, if you write to a file but someone then kills the processes using Task Manager the file won't get deleted.

另外,如果我没记错的话,没有简单的方法可以从 JVM 内部获取 Java 进程的 PID,所以不要尝试使用 PID 来制定解决方案.

Also, if I remember correctly there is no easy way of getting the PID of a Java process from inside the JVM so don't try and formulate a solution using PIDs.

这样的事情应该可以解决问题:

Something like this should do the trick:

private static final int PORT = 9999;
private static ServerSocket socket;    

private static void checkIfRunning() {
  try {
    //Bind to localhost adapter with a zero connection queue 
    socket = new ServerSocket(PORT,0,InetAddress.getByAddress(new byte[] {127,0,0,1}));
  }
  catch (BindException e) {
    System.err.println("Already running.");
    System.exit(1);
  }
  catch (IOException e) {
    System.err.println("Unexpected error.");
    e.printStackTrace();
    System.exit(2);
  }
}

此示例代码明确绑定到 127.0.0.1 应避免任何防火墙警告,因为此地址上的任何流量都必须来自本地系统.

This sample code explicitly binds to 127.0.0.1 which should avoid any firewall warnings, as any traffic on this address must be from the local system.

在选择端口时,尽量避免在知名端口列表中提到的端口.理想情况下,您应该在文件中或通过命令行开关配置使用的端口,以防发生冲突.

When picking a port try to avoid one mentioned in the list of Well Known Ports. You should ideally make the port used configurable in a file or via a command line switch in case of conflicts.

这篇关于如何允许一次只运行一个 Java 程序实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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