Search code examples
javacachingsynchronizedlocksdiskcache

Lock strategy in cache java


I'm developing disk cache (multithread). Cache can have many users at once. That is why I can write some rules:

1) Cache can't edit (or delete) file when client reads it.

2) When cache is editing file, clients should wait for the end of editing (and after read the file).

I need to organize this lock strategy with the help of java.

I read about synchronizatioan (synchronized block and java.util.concurrent.Locks) and as I understood it can't help here.

I tried to understand the FileLock. But when client reads file, cache lock can abort reading. And if clients will lock files before reading, there will be long sequence of client to read. I need for advice how to organize it (maybe another ways).

UPDATE

public void write(InputStream is) throws FileNotFoundException, IOException {

    File file = new File("path");

    try (FileOutputStream fos = new FileOutputStream(file);
            FileChannel filechannel = fos.getChannel();
            FileLock lock = filechannel.lock(0, Long.MAX_VALUE, false)) {

        // writing....

    }
}

public void read(OutputStream osToClient) throws IOException {

    File file = new File("path");

    try (FileInputStream fis = new FileInputStream(file);
            FileChannel filechannel = fis.getChannel();
            FileLock lock = filechannel.lock(0, Long.MAX_VALUE, true)) {

        IOUtils.copy(fis, osToClient);

    }

}

Solution

  • You should probably not build this yourself unless you do it for fun or for a school assignment. However, except that there are warnings about portability (so it may not work the way you expect on all platforms) FileLock should do the job. When you are reading, first get a shared lock on the file, read the file and release the lock when done, ideally in a try-with-resources block. When you are writing, get an exclusive lock (shared=false) instead. There can be multiple readers but only one writer, and when there is a writer there can be no readers.