java 单开程序,如何实现单实例Java应用程序?

Sometime I see many application such as msn, windows media player etc that are single instance applications (when user executes while application is running a new application instance will not created).

In C#, I use Mutex class for this but I don't know how to do this in Java.

解决方案

If I believe this article, by :

having the first instance attempt to open a listening socket on the localhost interface. If it's able to open the socket, it is assumed that this is the first instance of the application to be launched. If not, the assumption is that an instance of this application is already running. The new instance must notify the existing instance that a launch was attempted, then exit. The existing instance takes over after receiving the notification and fires an event to the listener that handles the action.

Note: Ahe mentions in the comment that using InetAddress.getLocalHost() can be tricky:

it does not work as expected in DHCP-environment because address returned depends on whether the computer has network access.

Solution was to open connection with InetAddress.getByAddress(new byte[] {127, 0, 0, 1});

Probably related to bug 4435662.

I also found bug 4665037 which reports than Expected results of getLocalHost: return IP address of machine, vs. Actual results : return 127.0.0.1.

it is surprising to have getLocalHost return 127.0.0.1 on Linux but not on windows.

Or you may use ManagementFactory object. As explained here:

The getMonitoredVMs(int processPid) method receives as parameter the current application PID, and catch the application name that is called from command line, for example, the application was started from c:\java\app\test.jar path, then the value variable is "c:\\java\\app\\test.jar". This way, we will catch just application name on the line 17 of the code below.

After that, we search JVM for another process with the same name, if we found it and the application PID is different, it means that is the second application instance.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值