Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure only one instance of a java program can be executed? [duplicate]

Tags:

It is requited that only one instance of a JAVA program can be executed at a certain time. I have observed a good number of solutions proposed in stack overflow in different earlier posts.

The solutions are based on:

  • By opening socket: To open a socket connection.
  • Based on the file locking: To create a temporary file and to hold a lock. And to add a shutdown hook to unlock that file when the JVM shuts down.

I do not want to use port locking as it can cause a possible conflict in ports usage.

So I was thinking to use file locking. After searching a bit, I have found the proponents of the port locking based mechanism has mentioned file locking can be unreliable if application crashes and for other IO errors.

What I need is to find a solution which will work consistently in cross platform and in multiple JDK. My intended platform is Windows and Linux and JDK is Sun and IBM JDK.

Can anyone shed some light on to this?