6

我正在创建一个用于打开和编辑 xml 文件的简单应用程序。这些文件位于应用程序的多个实例访问的本地文件夹中。我想要做的是锁定应用程序实例打开的每个文件,以便其他实例无法访问它。

为此,我使用以下代码:

函数无效读取文件(){

   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");
   }  

}

因为我想在这段时间内保持对正在编辑的文件的锁定,所以我没有关闭 raf 也没有释放 fl。

此时,尝试访问锁定文件的应用程序的任何其他实例都无法这样做。到目前为止,一切都很好。

我观察到以下奇怪的事情:

如果在获得文件锁定后,我在同一个文件上打开 FileInputStream,即使 FileLock 对象仍然有效(isValid 返回 true),应用程序的其他实例现在也可以访问正在编辑的文件。

我觉得这种行为很奇怪。谁能解释为什么会这样?

我希望以上内容有意义。提前致谢!

4

1 回答 1

7

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.

于 2010-03-19T20:01:50.630 回答