Prevent launching multiple instances of a java application

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.

Leave a Comment