How to allow running only one instance of a Java program at a time?

前端 未结 9 2206
南旧
南旧 2020-11-30 00:07

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

相关标签:
9条回答
  • 2020-11-30 00:47

    I think that the better idea would be to use file lock (quite an old idea :) ). Since Java 1.4 a new I/O library was introduced, that allows file locking.

    Once the application starts it tries to acquire lock on a file (or create it if does not exist), when the application exits the lock is relased. If application cannot acquire a lock, it quits.

    The example how to do file locking is for example in Java Developers Almanac.

    If you want to use file locking in Java Web Start application or an applet you need to sing the application or the applet.

    0 讨论(0)
  • 2020-11-30 00:48

    I've create the cross platform AppLock class.

    http://mixeddev.info/articles/2015/02/01/run-single-jvm-app-instance.html

    It is using file lock technique.

    Update. At 2016-10-14 I've created package compatible with maven/gradle https://github.com/jneat/jneat and explained it here http://mixeddev.info/articles/2015/06/01/synchronize-different-jvm-instances.html

    0 讨论(0)
  • 2020-11-30 00:51

    We do the same in C++ by creating a kernal mutex object and looking for it at start up. The advantages are the same as using a socket, ie when the process dies/crashes/exits/is killed, the mutex object is cleaned up by the kernel.

    I'm not a Java programmer, so I am not sure whether you can do the same kind of thing in Java?

    0 讨论(0)
提交回复
热议问题