Prevent launching multiple instances of a java application

I want to prevent the user from running my java application multiple times in parallel.

To prevent this, I have created a lock file when am opening the application, and delete the lock file when closing the application.

When the application is running, you can not open an another instance of jar. However, if you kill the application through task manager, the window closing event in the application is not triggered and the lock file is not deleted.

How can I make sure the lock file method works or what other mechanism could I use?


Solution 1:

You could use a FileLock, this also works in environments where multiple users share ports:

String userHome = System.getProperty("user.home");
File file = new File(userHome, "my.lock");
try {
    FileChannel fc = FileChannel.open(file.toPath(),
            StandardOpenOption.CREATE,
            StandardOpenOption.WRITE);
    FileLock lock = fc.tryLock();
    if (lock == null) {
        System.out.println("another instance is running");
    }
} catch (IOException e) {
    throw new Error(e);
}

Also survives Garbage Collection. The lock is released once your process ends, doesn't matter if regular exit or crash or whatever.

Solution 2:

Similar discussion is at http://www.daniweb.com/software-development/java/threads/83331

Bind a ServerSocket. If it fails to bind then abort the startup. Since a ServerSocket can be bound only once, only single instsances of the program will be able to run.

And before you ask, no. Just because you bind a ServerSocket, does not mean you are open to network traffic. That only comes into effect once the program starts "listening" to the port with accept().

Solution 3:

I see two options you can try:

  1. Use a Java shutdown hook
  2. Have your lock file hold the main process number. The process should exist when you lanuch another instance. If it's not found in your system, you can assume that the lock can be dismissed and overwritten.