Problem with Java file locking mechanism (FileLock etc)

喜夏-厌秋 提交于 2019-11-28 01:07:13

问题


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!


回答1:


From the FileLock JavaDocs:

Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified.

Your platform is only providing advisory locking. Holding an advisory lock will not prevent other processes from accessing the file.

So, locking a file is really just hanging out a "Do not disturb" sign, but leaving the door unlocked. If everyone reads and honors the sign, you're good, but it doesn't stop anyone from just walking in.

The JavaDocs also explicitly states:

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.

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



来源:https://stackoverflow.com/questions/2479222/problem-with-java-file-locking-mechanism-filelock-etc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!