I'm developing a Java application. And I wanted to prevent a user to run simultaneously more instances of the same Java application. I used JUnique app locking library for Java and it works great. But has a serious issue when it crashes.
The application cannot be started if it crashes, it just returns AlreadyLockedException. The code I used to lock my application is below.
public static boolean isRunning() {
boolean alreadyRunning = false;
try {
JUnique.acquireLock(appId);
alreadyRunning = false;
} catch (AlreadyLockedException e) {
logger.error("Unable to acquire lock. There is an instance already running");
alreadyRunning = true;
} catch (Throwable t) {
logger.error("Unable to acquire lock. ", t);
}
return alreadyRunning;
}
And code to release my lock is:
public static void release() {
try {
JUnique.releaseLock(appId);
} catch (Throwable t) {
logger.error("Error releasing the lock", t);
}
}
I can use release() method for dealing with expected crashes. But the real problem occurs when application crashes unexpectedly during runtime. The application is terminated without releasing the acquired lock for application.
How can we release JUnique lock if the application unexpectedly crashes?