使用 Java FileLock 有多安全?

How safe is it to use Java FileLock?

使用 java.nio.channels.FileLock for locking files among processes? It is stated that other processes can not access the file if we have an exclusive lock. However, the below answer on another SO question 说明其他进程也必须检查文件锁以确保我们的进程安全。

(a) Are you aware that locking the file won't keep other processes from touching it unless they also use locks?

所以我测试了我的代码并尝试更改,一个我已经锁定的文件,使用 Windows 文本编辑器,我没有受到伤害但不是当我用 Notepad++..

测试时

在 Java 6 中是否有适当锁定文件的解决方案?

来自 java.nio.channels.FileLock 平台依赖项下的 Javadoc:

The native file-locking facilities of some systems are merely advisory, meaning that programs must cooperatively observe a known locking protocol in order to guarantee data integrity. On other systems native file locks are mandatory, meaning that if one program locks a region of a file then other programs are actually prevented from accessing that region in a way that would violate the lock. On yet other systems, whether native file locks are advisory or mandatory is configurable on a per-file basis. To ensure consistent and correct behavior across platforms, it is strongly recommended that the locks provided by this API be used as if they were advisory locks.

正如您从测试中发现的那样,您 Windows 版本上的其他 non-Java 代码 运行 不必遵守您的独占锁。

你唯一的解决办法是尽可能快地将文件读入内存,慢慢处理信息,然后尽可能快地将文件写入磁盘。

It is stated that other processes can not access the file if we have an exclusive lock.

它在哪里?Javadoc 中没有说明。

However, the below answer on another [SO question][2] states other processes have to check for the filelock too in order for our process to be safe.

没错。

So I tested my code and tried to change, a file which I have the lock already, with Windows Text Editor and I was safe from harm but not when I test with Notepad++.

通过在一个文件锁影响普通打开的平台上进行测试,您已经在做一些无效的事情,但由此得出的唯一结论是它不安全。 Notepad++ 保持文件打开,因此会遇到您的锁,但 Windows 文本编辑器不会,因此也不会看到锁,直到您尝试保存。

Is there a solution for locking a file appropriately in Java 6?

除非您要锁定的应用程序也使用文件锁。

Java FileLock 在许多平台上使用 advisory(不是 mandatory)锁。这意味着它 可能 仅提供针对其他也使用 FileLock(或其他语言中的等效项)的应用程序的锁定。

Linux 或 Windows 都没有全面实施强制锁定。例如:

  • 对于 Linux 和类似的文件锁定仅供参考。

  • 对于Windows,根据Wikipedia

    "For applications that use the file read/write APIs in Windows, byte-range locks are enforced .... by the file systems that execute within Windows. For applications that use the file mapping APIs in Windows, byte-range locks are not enforced ..."

    换句话说,锁定 Windows 可以是强制性的,也可以是建议性的,具体取决于 API Windows 应用程序使用哪个来访问文件。


How safe is it to use Java FileLock?

如果您实际上是在询问是否可以安全地假设 FileLock 为所有其他应用程序(Java 和 non-Java)提供强制文件锁定,无论它们如何书面上,答案是否定的。做出这样的假设是不安全的。


Is there a solution for locking a file appropriately in Java 6?

仅当所有应用程序(Java & other)合作时;例如通过使用 FileLock 或等价物。

如果您不能做出这样的假设,则没有使用便携式 Java 的解决方案。事实上,在大多数(如果不是全部)常见的 OS 平台上,根本没有解决方案,AFAIK ... 因为平台本身不支持独立于应用程序的强制文件锁定。