0

From what I have searched so far, I find 2 solutions.

  1. One is to create or reuse a file, then try to lock the file.

    File file = new File(lockFile);
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
    FileLock fileLock = randomAccessFile.getChannel().tryLock();
    if (fileLock == null) {
        // means someone have obtain the lock, therefore it is expected that an application is there
        System.exit(0);
    }
    

    Advantage of this approach:

    1. If the application is shutdown abnormally, OS will help us release the lock. We do not need to manually delete the file, in order to work.

    Source: How to implement a single instance Java application?

  2. Create a file, without any lock, just use the presence of the file to determine if an application is running or not. Disadvantage of this approach:

    1. If application shutdown abnormally, we need to manually remove the file, in order to work.

Though I personally think this is worse option compared to 1, however it seems library use this approach more often. For example, Play Framework (RUNNING_PID file).

So can someone suggest why framework seem to suggest use of 2 over 1? What are the advantages of such approach?

In addition, is the selection choice depends on performance and ease of use. For example, client side application should choose 1 and server side application should choose 2?

CHANist
  • 1,302
  • 11
  • 36
  • 1
    I agree with the person who raised this issue: https://github.com/playframework/playframework/issues/10419 – tgdavies Jul 06 '22 at 03:38
  • If you have write access to the system then option 1 is a good bet. See the accepted answer here for some other options and relevant reading: [How to implement a single instance Java application?](https://stackoverflow.com/questions/177189/how-to-implement-a-single-instance-java-application) – sorifiend Jul 06 '22 at 03:38
  • 1
    Why tag this swing and JavaFX if it is not UI related? Anyway, in case you actually are using JavaFX and if you want a single instance JavaFX app, there is an [alternate solution using a socket here](https://stackoverflow.com/questions/41051127/javafx-single-instance-application). – jewelsea Jul 06 '22 at 04:09
  • 1
    A lot of applications do not use a lockfile but a pidfile instead. If the pid points to the correct application it is running - if not it is outdated and may be ignored. Bad is if it gets deleted despite the application is running. – Queeg Jul 06 '22 at 07:13
  • Could you elaborate more? Why so many application hesitate to use a lockfile? – CHANist Jul 06 '22 at 07:29

0 Answers0