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

查看:868
本文介绍了如何允许一次只运行一个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?

btw。目标平台是带有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.

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

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天全站免登陆