I am creating a simple application for opening and editing xml files. These files are located in a local folder accessed by several instances of the application. I want to lock every file that is opened by the application instance so that other instances cannot access it.
For 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 the lock on the edited file to last, I do not close raf and do not release fl.
At this point, any other application instance trying to access a locked file cannot do this. So far so good.
I noticed the following strange thing:
If, after acquiring a file lock, I open FileInputStream in the same file, although the FileLock object remains valid (isValid returns true), other application instances can now access the file being edited.
I find this behavior strange. Can anyone explain why this is happening?
I hope this makes sense. Thanks in advance!
source share