The way it is often done in unix systems is to create a file, which is an atomic operation and then check whether the file could be created or not. If it was possible to create the file then that process has the lock and is allowed to run. If the file could not be created, someone else must have the lock and the instance terminates promptly. The code for such a thing
private boolean lock()
{
try
{
final File file=new File("bpmdj.lock");
if (file.createNewFile())
{
file.deleteOnExit();
return true;
}
return false;
}
catch (IOException e)
{
return false;
}
}
in the main of the app you then start with
if (!lock())
{
System.out.println("Cannot lock database. Check that no other instance of BpmDj is running and if so, delete the file bpmdj.lock");
return;
}
Of course, there are two caveats to be mentioned. First of all: if the app crashes hard, then the file will very likely not be deleted, resulting in some inconvenience for the user (he will need to remove the lockfile himself).
Secondly: the java documentation states the following:
createNewFile
atomically creates a new, empty file ... if and only
if a file with this name does not yet exist. The check for the
existence of the file and the creation of the file if it does not
exist are a single operation that is atomic with respect to all other
filesystem activities that might affect the file. Note: this method
should not be used for file-locking, as the resulting protocol cannot
be made to work reliably. The FileLock facility should be used
instead.
Especially the last note is interesting because in this case we don't really use it for file-locking, merely to check that no other instances of the same application are present. Yet I'm a bit curious to understand why they write that the 'resulting protocol cannot be made to work reliable'