I am creating a simple application for opening and editing xml files. These files are located in a local folder accessed by multiple instances of the application. What I want to do is lock each file that is opened by an instance of the app, so that other instances cannot access it.
To achieve this I use the following code:
function void readFile(){
File xmlFile = new File("myFile.xml");
RandomAccessFile raf = new RandomAccessFile(xmlFile, "rw");
FileLock fl = raf.getChannel().tryLock();
if(fl==null){
System.out.println("file already locked by another instance");
}else{
setCurrentFile(raf);
setLock(fl);
System.out.println("file successfully locked by this instance");
}
}
Since I want to keep the lock on the file being edited for the duration I do not close the the raf nor release the fl.
At this point any other instance of the app that tries to access the locked file fails to do so. So far so good.
I have observed the following strange thing:
If after acquiring the lock on the file, I open a FileInputStream on the same file, even though the FileLock object remains valid (isValid returns true), other instances of the app can now access the file being edited.
I find this behaviour strange. Could anyone explain why this happens?
I hope the above make sense. Thanks in advance!