如果仍然抛出 OverlappingFileLockException,等待 FileChannel.lock 的目的是什么?

What's the purpose of waiting in FileChannel.lock if OverlappingFileLockException is thrown anyway?

FileChannel.lock 允许在 Java 中创建文件锁(我使用 How can I lock a file using java (if possible)FileOutputStream 的方法以避免 NonWritableChannelException):

FileOutputStream out = new FileOutputStream(file);
try {
    java.nio.channels.FileLock lock = out.getChannel().lock();
    try {
        ...
    } finally {
        lock.release();
    }
} finally {
    out.close();
}

处理等待持有资源的进程释放锁的重要部分。因此lock

will block until the region can be locked, this channel is closed, or the invoking thread is interrupted, whichever comes first.

但是,每次我尝试锁定同一个文件(跨越整个文件的区域)时,我都会得到一个 OverlappingFileLockException 抛出

If a lock that overlaps the requested region is already held by this Java virtual machine, or if another thread is already blocked in this method and is attempting to lock an overlapping region

这与锁定的逻辑相矛盾,并且无法使用文件锁,因为如果只允许队列中的一个线程(更多线程立即抛出 OverlappingFileLockException),则必须手动同步资源访问。

使用 lock(0, Long.MAX_VALUE, false),其中 false 指的是 shared 属性 不会改变此行为。

File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.

阅读"They cannot be used for controlling because only one lock per JVM can be acquired"。

"Suitable" 在这种情况下可能意味着很多事情,包括与基于线程的锁相比效率低下的概念。从多个线程访问文件时,必须使用它们来保护文件锁。