J Fabian Meier
J Fabian Meier

Reputation: 35805

Locking in concurrent access on file system

Say two different Java programs are trying to read and/or write data from or to the same directory (Windows or Linux).

They should not do it simultaneously. How can one ensure that?

My best idea so far is to create an empty file lock before starting to use the directory and remove it afterwards. But checking for the existence of the file and writing it is non-atomic, so this may fail.

Upvotes: 1

Views: 237

Answers (2)

user15270043
user15270043

Reputation:

Look at Double-Checked Locking algorithm. For example:

    public boolean tryLock() {
        if (!isFolderLockedByOtherProcess()) {
            lockFolder();
            if (isFolderLockedByMe()) {
                return true;
            }
        }
        return false;
    }

Upvotes: 0

M A
M A

Reputation: 72854

The Files.createFile() does such an atomic operation:

Creates a new and empty file, failing if the file already exists. The check for the existence of the file and the creation of the new file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the directory.

Upvotes: 4

Related Questions