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);
}
}