java - 在 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();
buffer
在ByteBuffer
此代码之前填充了一些数据。
因此,此代码在一个线程中定期完成,并且没有其他线程正在使用此锁或访问同一文件。发生的情况是,当我在程序运行时使用记事本访问文件时,有时会得到OverlappingFileLockException
. 如果我捕捉到该异常,即使我关闭记事本,线程也会循环并一遍又一遍地生成相同的异常。我有时也会收到错误:The requested operation cannot be performed on a file with a user-mapped section open
,它可能与也可能不相关OverlappingFileLockException
,但有时出于相同的原因发生,当我在程序运行时使用记事本打开文件或打开文件属性时。
解决方案
即使写入尝试引发 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();
}
推荐阅读
- java - java 标志 Xms 和 Xmx 是否覆盖标志 XX:+UseCGroupMemoryLimitForHeap?
- iis - IIS 没有为 .NET Core 使用正确的版本 - 如何管理?
- mongodb - 如何使用 Spring Boot 框架使用 Elasticsearch 搜索功能并通过 MongoDB 进行插入?
- c++ - 在 MinGW 中使用 DLL 包装 Windows PackageManager
- tcl - 在 TCL/Tk tablelist 单元格中格式化字符串的一部分
- c# - 为多用户 windows 应用程序设置服务器 IP
- java - 带有特殊字符(“\N”、“\S”和“\T”)的 JDBC 查询插入
- java - 如何检查列表列表中的对象是否为空或空?
- angular - Angular 6 - 从表单外部验证和提交表单
- jquery - 为什么 React 的性能优于使用 JQuery 的直接 DOM 操作?