【发布时间】:2023-04-09 20:07:01
【问题描述】:
这是有问题的代码部分:
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 相关,也可能不相关,但有时会出于同样的原因发生,当我在程序运行时使用记事本打开文件或打开文件属性时。
【问题讨论】:
-
当你说“定期”时,你是怎么做到的?
-
代码在while循环中。在循环结束时,线程休眠 100 毫秒。
标签: java nio filechannel filelock