Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 431
Sathish Avatar asked Aug 12 '11 05:08

Sathish


People also ask

How do I run multiple instances of a program in Java?

The command line arguments are stored in Eclipse in a Run Configuration (menu: Run > Run Configurations... , or Run > Debug Configurations... ). Just create two of them, reference the same main class, and specify different command line arguments, e.g. to specify different ports, then Run / Debug both of them.


1 Answers

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.

like image 71
Manuel Avatar answered Sep 23 '22 10:09

Manuel