首页 > 解决方案 > 在 Java 中锁定文件通道时出现 OverlappingFileLockException

问题描述

这是有问题的代码部分:

FileChannel fileChannel = FileChannel.open(filePath, StandardOpenOption.WRITE);
fileChannel.force(true);
FileLock lock = fileChannel.lock();
fileChannel.truncate(0);
fileChannel.write(buffer);
lock.release();
fileChannel.close();

bufferByteBuffer此代码之前填充了一些数据。

因此,此代码在一个线程中定期完成,并且没有其他线程正在使用此锁或访问同一文件。发生的情况是,当我在程序运行时使用记事本访问文件时,有时会得到OverlappingFileLockException. 如果我捕捉到该异常,即使我关闭记事本,线程也会循环并一遍又一遍地生成相同的异常。我有时也会收到错误:The requested operation cannot be performed on a file with a user-mapped section open,它可能与也可能不相关OverlappingFileLockException,但有时出于相同的原因发生,当我在程序运行时使用记事本打开文件或打开文件属性时。

标签: javaniofilechannelfilelock

解决方案


即使写入尝试引发 I/O 异常,也要确保释放锁。

FileChannel fileChannel = FileChannel.open(filePath, 
StandardOpenOption.WRITE);
fileChannel.force(true);

FileLock lock = fileChannel.lock();
try {
  fileChannel.truncate(0);
  fileChannel.write(buffer);

} finally {
  lock.release();
  fileChannel.close();
}

推荐阅读