Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using java FileChannel FileLock to prevent file writes but allow reads

I think I'm misunderstanding how the FileChannel's locking features work.

I want to have an exclusive write lock on a file, but allow reads from any process.

On a Windows 7 machine running Java 7, I can get FileChannel's lock to work, but it prevents both reads and writes from other processes.

How can I achieve a file lock that disallows writes but allows reads by other processes?

like image 585
Jason S Avatar asked Mar 25 '14 21:03

Jason S


1 Answers

  • FileChannel.lock() deals with file regions, not with the file itself.
  • The lock can be either shared (many readers, no writers) or exclusive (one writer and no readers).

I guess you are looking for a bit different feature - to open a file for writing while allowing other processes to open it for reading but not for writing.

This can be achieved by Java 7 FileChannel.open API with non-standard open option:

import static java.nio.file.StandardOpenOption.*;
import static com.sun.nio.file.ExtendedOpenOption.*;
...
Path path = FileSystems.getDefault().getPath("noshared.tmp");
FileChannel fc = FileChannel.open(path, CREATE, WRITE, NOSHARE_WRITE);

Note ExtendedOpenOption.NOSHARE_WRITE which is a non-standard option existing in Oracle JDK.

like image 64
apangin Avatar answered Sep 29 '22 05:09

apangin