Problem with Java file locking mechanism (FileLock, etc.)

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!

+4
source share
1 answer

From FileDock JavaDocs:

Regardless of whether the actual blocking of another program blocks access to the contents of the locked area, it depends on the system and therefore is not indicated.

Your platform provides only advisory locking. Holding a control lock will not prevent other processes from accessing the file.

So, the file lock is actually just hanging over the Do Not Disturb icon, but leaving the door unlocked. If everyone reads and honors the sign, you are good, but that does not stop anyone from just walking.

JavaDocs also explicitly states:

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

If your code is running on an application server, file locking will not do what you need.

+7
source

Source: https://habr.com/ru/post/1304593/


All Articles