CHANist
CHANist

Reputation: 1402

Best Way to implement Single Java Application Instance

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?

Upvotes: 0

Views: 142

Answers (0)

Related Questions