1

I have some code to ensure a single instance of my app is running, using a lock file:

public static boolean ensureSingleInstance(String appName) {
    try {
        String path = Paths.get(System.getProperty("java.io.tmpdir"),  appName + ".lock").toString();
        File file = new File(path);
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        if (randomAccessFile.getChannel().tryLock() != null) {
            file.deleteOnExit();
            return true;
        }
    } catch (IOException ignore) {
    }
    return false;
}

This works 99.9% of the time. And then yesterday, in production, a second instance of the app successfully started...

How can this code fail?

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
Will
  • 73,905
  • 40
  • 169
  • 246
  • 1
    Different value of the system property, different value of the app name...? – Andy Turner Nov 17 '17 at 09:15
  • 2
    The obvious ones that you probably checked are a) different values for the ``getProperty`` call or b) a different ``appName`` (case sensitive etc) – f1sh Nov 17 '17 at 09:15
  • 1
    @AndyTurner the fact that this isnt an exact copy+paste of the actual code makes answering this question even harder – f1sh Nov 17 '17 at 09:18
  • Does the file exist on the same device the processes are running? – Nir Alfasi Nov 17 '17 at 09:20
  • What happens when `ensureSingleInstance` returns false? – StephaneM Nov 17 '17 at 09:27
  • @StephaneM the app exits if it returns false. – Will Nov 17 '17 at 09:59
  • @f1sh the only thing I did was bowdlerize the appName; all instances use the same hard-coded appName, and I'm having a hard job imagining that `System.getProperty("java.io.tmpdir")` changes under me :( – Will Nov 17 '17 at 10:00
  • The code itself looks like [this](https://stackoverflow.com/a/2002948/507738). So we can assume that that solution actually works. The only thing I can imagine is indeed that the value of either `appName` or `System.getProperty("java.io.tmpdir")` actually changed. – MC Emperor Nov 17 '17 at 10:08
  • @MCEmperor I think I got it https://community.oracle.com/thread/2044019 - its about the same. Hmm, yeah I can't spot any race anywhere else :( – Will Nov 17 '17 at 10:11

0 Answers0