Java文件锁定机制(FileLock等)的问题
我正在创建一个简单的应用程序来打开和编辑 xml 文件。 这些文件位于可由应用程序的多个实例访问的本地文件夹中。 我想要做的是锁定应用程序实例打开的每个文件,以便其他实例无法访问它。
为了实现这一点,我使用以下代码:
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");
}
}
因为我想在编辑期间保持对正在编辑的文件的锁定,所以我不关闭 raf 也不释放 fl。
此时,尝试访问锁定文件的应用程序的任何其他实例都无法执行此操作。到目前为止,一切都很好。
我观察到以下奇怪的事情:
如果在获取文件锁定后,我在同一个文件上打开 FileInputStream,即使 FileLock 对象仍然有效(isValid 返回 true),应用程序的其他实例现在可以访问该文件编辑。
我觉得这种行为很奇怪。 谁能解释为什么会发生这种情况?
我希望以上说得有道理。 提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 FileLock JavaDocs:
您的平台仅提供咨询锁定。持有咨询锁不会阻止其他进程访问该文件。
因此,锁定文件实际上只是挂出“请勿打扰”的标志,但不锁门。如果每个人都阅读并尊重这个标志,那么你就很好,但这并不能阻止任何人走进去。JavaDocs
还明确指出:
如果您的代码在应用程序服务器中运行,文件锁定将无法满足您的需要。
From the FileLock JavaDocs:
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:
If your code is running in an application server, file locking will not do what you need.