Java文件锁,用于多进程的读写操作。

huangapple 未分类评论68阅读模式
标题翻译

Java file lock for read and write with multiple processes

问题

在我的应用程序中,多个进程尝试对文件进行读写访问。每个应用程序都有一个单独的线程。我需要确保任何两个进程不会同时访问该文件。我正在使用JDK中的FileLock。当一个进程获得锁并且其他进程尝试访问文件(进行读取或写入)时,一切都运行正常,会抛出异常,说明文件已被其他进程锁定。

现在,我需要确保对于第二个进程,而不是抛出异常,线程应该等待,直到第一个进程释放锁定,一旦锁定被释放,就可以继续进行工作。

我该如何做到这一点?到目前为止,我还没有找到实现这一点的方法。

英文翻译

In my application multiple processes are trying access a file for read and write. Every application has a single thread. I need to make sure that no 2 processes are accessing the file at the same time. I am using FileLock in JDK. This works fine, when one process has acquired the lock and other process tries to access to the file (for read or write) exception is thrown stating file has been locked by other process.

Now i need to make sure that, for 2nd process rather then throwing the exception thread should wait till lock is released by first process and once lock is released continue with its work.

How can I do this. So, fat I have not been able it figure out someway of doing this.

答案1

得分: 0

你考虑过实现类似以下的内容吗?

while (true) {
   尝试获取锁 - {
     // 如果获取到锁,跳出循环

   } catch (Exception) {
     记录... 异常
     可能等待一段时间
  }
}
英文翻译

Have you considered implementing something like below?

while (true) {
   try to acquire lock - {
     // if the lock is acquired break the loop     

   } catch (Exception) {
     log... exception
     possibly wait for sometime
  }
}

huangapple
  • 本文由 发表于 2020年3月16日 16:07:14
  • 转载请务必保留本文链接:https://java.coder-hub.com/60702304.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定