如何安全地更新具有许多读者和一个作者的文件? [英] How to safely update a file that has many readers and one writer?

查看:188
本文介绍了如何安全地更新具有许多读者和一个作者的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组文件。该组文件是只读NTFS共享,因此可以有很多读者。

I have a set of files. The set of files is read-only off a NTFS share, thus can have many readers. Each file is updated occasionally by one writer that has write access.

如何确保:


  1. 如果写入失败,上一个文件仍可读取

  2. 读者无法持有单个作者

我使用的是Java,我目前的解决方案是写入器写入一个临时文件,然后用现有的文件使用 File.renameTo() code>。问题是在NTFS上, renameTo 失败如果目标文件已经存在,所以你必须自己删除它。但是如果写入程序删除目标文件,然后失败(计算机崩溃),我没有可读的文件。

I am using Java and my current solution is for the writer to write to a temporary file, then swap it out with the existing file using File.renameTo(). The problem is on NTFS, renameTo fails if target file already exists, so you have to delete it yourself. But if the writer deletes the target file and then fails (computer crash), I don't have a readable file.

nio的FileLock只能使用相同

nio's FileLock only work with the same JVM, so it useless to me.

如何使用Java安全地更新包含许多读者的文件?

How do I safely update a file with many readers using Java?

推荐答案

根据 JavaDoc


此文件锁定API适用于
到基本操作
系统的本地锁定
设施。因此,保存在文件
上的锁对于
有权访问该文件的所有程序都是可见的,而不管
是哪些程序
被写入的语言。

This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written.

这篇关于如何安全地更新具有许多读者和一个作者的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆