简体   繁体   中英

Getting OverlappingFileLockException when locking file channel in Java

Here's the part of the code that is problematic:

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 is a ByteBuffer that was filled with some data prior to this code.

So, this code is done periodically in one thread and no other threads are using this lock or accesing the same file. What happens is when I access the file with notepad while the program is running, I sometimes get the OverlappingFileLockException . If I catch that exception, the thread will loop and generate the same exception over and over again, even if I close the notepad. I also sometimes get the error: The requested operation cannot be performed on a file with a user-mapped section open , which might or might not be related to OverlappingFileLockException , but it sometimes happens for the same reason, when I open the file with notepad or open file properties while the program is running.

Make sure to release the lock even when an I/O exception is thrown from write attempts.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM