Search code examples
javamultithreadingdouble-checked-locking

Check if file exists on server and return that file content


I want to check if the file exist on server on multithread environment and if exists return that file content diractly or download from my s3 service server.

My code like this:

final Object lock = new Object();
File file = new File("/file/path");
if (file.exists()) {
    return FileUtils.readFileToByteArray(file);
} else {
    byte[] bytes = this.downloadFileFromRemoteServer();
    if (!file.exists()) {
        synchronized (lock) {
            if(!file.exists()) {
                FileUtils.writeByteArrayToFile(tempFile, bytes);
            }
        }
    }
    tempFile.renameTo(file);
    return bytes;
}

The above code similar java double checked locking, is method file.exists() behavior like volatile keyword? And pseudo code correctly?


Solution

  • File.exists() checks the file existence with the file-system, and so it should behave like a volatile, so you are covered there

    Some issues though -

    1) As soon as a thread sees that the file doesn't exist, it starts downloading the file, which is time consuming, so its likely that other threads will also come and start downloading the same file. So the download part should be moved inside the lock

    2) You're renaming the temp file outside the lock. A thread may get to that point without creating/writing-to a temp file. Should move the rename inside the lock as-well

    Since IO has much more overhead than locking, I think the above 2 steps would be beneficial