-1

I'm implementing a quick file server using Java RMI, which has 2 remote methods, one is for reading a file from the server and the other is for writing it to the client.

I want to lock concurrent access to same file. For example, if 10 users concurrently call read() and write() remote methods, specifying the same file: 'foo.txt', I need that the first call to be completely executed before the second call does, and the second call is completely executed before the third call does...

If I use "syncronized" statement in the two RMI methods, I lose efficiency if different users concurrently call these methods, specifying different files.

On the other hand, I can't use the FileLock class because:

"File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine."

and in RMI, there is only one process in the same JVM, that executes new threads for each remote call.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Juan
  • 9
  • 2
  • I suggest a remote object instance per file, and method synchronization. But file reads and writes are atomic at the OS level. – user207421 Mar 16 '21 at 03:12

1 Answers1

0

You could make use of ReadWriteLock to handle read/write locks of the Path of each file - but only if you don't run multiple processes of your RMI server or expect those files to be changed outside one RMI server VM. Each of the entry points for read or write needs to locate ReentrantReadWriteLock for the Path provided such as using getReadWriteLock(Path) here:

private static ConcurrentHashMap<Path,ReentrantReadWriteLock> LOCKS = new ConcurrentHashMap<>();
private static ReentrantReadWriteLock getReadWriteLock(Path path) {
    return LOCKS.computeIfAbsent(path, p -> new ReentrantReadWriteLock());
}

Then your own code can use the readLock() or writeLock() API calls to allow multiple readers when there are no writes taking place. Over time you'd need to do some housekeeping to purge entries which are no longer in use.

DuncG
  • 12,137
  • 2
  • 21
  • 33