相应地锁定和更新文件
注意:我已阅读有关如何锁定和解锁文件的其他帖子。我没有发现任何我不知道的特别之处。因此,我将把我的场景放在这里,以便更好地理解手头的问题。
根据我的经验,当来自多个 jvm 实例的不同对象尝试锁定和更新文件时,FileChannel.lock 不能保证文件的锁定和解锁。
我的应用程序中的场景是 - 有三个单独的程序更新文件。这些程序正在不同的 jvm 实例上运行。假设程序是 A、B 和 C;文件是 F。如果 A 锁定文件 F,B 和 C 应该等待 F 被释放,然后其他程序之一才能获取它。如果程序在同一个 jvm 实例上运行,则此方法可以正常工作。不幸的是,这在多个 jvm 实例中不起作用。
我有另一个想法,那就是有一个平面文件,我可以在其中指示 F 是否应该更新。该平面文件的内容可以是锁定的或解锁的。默认/初始值将被解锁。因此,当其中一个程序想要更新 F 时,它需要查看平面文件中的标志。如果标志读取为 LOCKED,则应等待。但在这种方法中,存在一个问题 - 如果多个程序同时打开平面文件并看到“UNLOCKED”,或者两个等待平面文件读取“UNLOCKED”的程序同时看到文件读取“,该怎么办?解锁”?
有什么想法吗?
Note: I have read other posts on how to lock and unlock a file. I didn't find anything special that I wasn't aware of. So I am gonna put my scenario here to better appreciate the problem on hand.
In my experience, FileChannel.lock doesn't guarantee locking and unlocking of a File when different Objects from multiple instances of jvm are trying to lock and update the file.
The scenario in my application is - there are three separate programs that update a file. Those programs are being run on different jvm instances. Say the programs are A, B, and C; and the file is F. If A locks the file F, B and C should wait for F to be released before one of the other programs can get a hold of it. This works fine if the programs are run on the same jvm instance. Unfortunately this doesn't work in multiple jvm instances.
I had another idea which was to have a flat file where I'd indicate if F should be updated. The content of that flat file can be either LOCKED or UNLOCKED. Default/initial value would be UNLOCKED. So, when one of the programs would want to update F, it needs to see the flag in the flat file. If flag reads LOCKED, it should wait. In this approach, there's a problem though - what if multiple programs open the flat file exactly at the same time and see "UNLOCKED" or two programs that were waiting for the flat file to read UNLOCKED and exactly at the same time see file reads "UNLOCKED"?
Any idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果需要锁定文件系统,则必须创建一个目录。目录存在意味着“锁定”,缺少目录意味着未锁定。
原因是创建和删除目录在任何文件系统中都必须是原子操作。因此,一旦两个进程尝试创建同一目录,其中一个就会出错。
If you need locking in a filesystem, then you must create a directory. Directory exists means "locked", missing directory means unlocked.
The reason is that creating and deleting directories must be atomic operations in any filesystem. So as soon as two processes try to create the same directory, one of them will get an error.