Jason S
Jason S

Reputation: 189626

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?

Upvotes: 5

Views: 1788

Answers (1)

apangin
apangin

Reputation: 98284

  • 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.

Upvotes: 6

Related Questions