原子文件写入操作(跨平台) [英] Atomic file write operations (cross platform)

查看:134
本文介绍了原子文件写入操作(跨平台)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何建立原子文件写入操作?该文件将由Java服务编写,并由python脚本读取。

对于记录,读取远远大于写入。但写作分批发生,往往很长。文件大小相当于兆字节。

How do I build up an atomic file write operation? The file is to be written by a Java service and read by python scripts.
For the record, reads are far greater than writes. But the write happens in batches and tend to be long. The file size amounts to mega bytes.

现在我的做法是:


  • 将文件内容写入
    相同目录中的临时文件

  • 删除旧文件

  • 将临时文件重命名为旧文件名。

这是正确的方法吗?如何避免旧文件被删除但新文件名尚未重命名的条件?

Is this the right approach? How can avoid conditions where the old file is deleted but the new filename is yet to be renamed?

使用这些编程语言(python和java )提供了锁定和避免这种情况的构造?

Do these programming languages (python and java) offer constructs to lock and avoid this situation?

推荐答案

AFAIK no。

AFAIK no.

原因是为了使这种原子操作成为可能,必须以事务文件系统的形式支持操作系统。而且主流操作系统都没有提供交易文件系统。

And the reason is that for such an atomic operation to be possible, there has to be OS support in the form of a transactional file system. And none of the mainstream operating system offer a transactional file system.

编辑 - 至少符合POSIX标准的系统是错误的。如果具有目标名称的文件已经存在,则POSIX 重命名 syscall将执行原子替换,如@janneb所指出。这应该足以做原子的OP操作。

EDIT - I'm wrong for POSIX-compliant systems at least. The POSIX rename syscall performs an atomic replace if a file with the target name already exists ... as pointed out by @janneb. That should be sufficient to do the OP's operation atomically.

然而,事实依然是Java File.renameTo()方法明确地保证是原子的,所以它不能为OP的问题提供跨平台的解决方案。

However, the fact remains that the Java File.renameTo() method is explicitly not guaranteed to be atomic, so it does not provide a cross-platform solution to the OP's problem.

这篇关于原子文件写入操作(跨平台)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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