-1

I'm working on a program in Java where a read/write lock is required. The scenario is multiple processes can write to the file at the same time. I have used the following line to lock the File.

FileOutputStream fos = new FileOutputStream(file);
FileLock lock = fos.getChannel().lock;

This works fine when multiple processes try to write to the file simultaneously. The other processes are waiting till the lock is released. However, the other processes are still able to read this file and when they open the InputStreamReader to read this file, the initial process which is writing to this file stops and the read process starts. I want the read process also to be synchronized.

Can someone help me with this. (This runs on multiple processes and also threads)

Sri
  • 573
  • 2
  • 6
  • 20
  • One look at the [documentation](https://docs.oracle.com/javase/8/docs/api/java/nio/channels/FileChannel.html#lock--) would have revealed that `lock()` obtains an exclusive lock. – VGR Feb 27 '16 at 00:03

1 Answers1

0

Try to use another form of FileChannel#lock method

public abstract FileLock lock(long position, long size, boolean shared)

Use this method with the last shared parameter with true value like this

FileLock lock = fos.getChannel().lock(0L, Long.MAX_VALUE, true);

As described shared parameter in JavaDoc

shared - true to request a shared lock, in which case this channel must be open for reading (and possibly writing); false to request an exclusive lock, in which case this channel must be open for writing (and possibly reading)

By default, the parameter has false value and your file is shared exclusively.

Andriy Kryvtsun
  • 3,220
  • 3
  • 27
  • 41