So i used the following to create a lock on a file so that I can edit it exclusively:
File file = new File(filename);
channel = new RandomAccessFile(file, "rw").getChannel();
lock = channel.tryLock();
Now I have a 2nd thread want to access the same file - just to read, not edit. How do i do that? Right now the 2nd thread will throw an io exception and inform me the file is locked.
Is this doable? Any suggestions? Thanks
解决方案
You could try asking for a shared lock using the three argument version of tryLock.
Basically instead of doing
lock=channel.tryLock()
you would do lock = channel.trylock(0, Long.MAX_VALUE, true)
As an aside, you should be careful with file locking in java. While you can guarantee the locks behave as expected within the JVM you can't necessarily be sure that they will behave as expected accross multiple processes.