Unable to lock files on Linux using java.nio.channels.FileLock

后端 未结 6 1165
花落未央
花落未央 2020-12-11 20:34

I was creating an application in Java for which I want only one instance running. For this purpose I created a file and got a lock while my application is running.

I

6条回答
  •  情深已故
    2020-12-11 20:57

    Use mkdir. On unix systems this is an atomic operation – it will succeed if a new directory is successfully created, otherwise it will fail.

    Example:

    File lockFile = new File("/path/to/lockdir");
    boolean hasLock = lockFile.mkdir();
    if (!hasLock) {
      throw new IOException("could not get lock");
    }
    // do stuff
    lockFile.delete();
    

提交回复
热议问题