0

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.

A6SE
  • 177
  • 1
  • 11

1 Answers1

1

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();
}
Alexandre Dupriez
  • 3,026
  • 20
  • 25
  • Thank you, that solved the problem and the program continues running normally. However do you know what causes such exception? Shouldn't the lock prevent even notepad from accessing the file or if the notepad is opened before the lock, the program waits at the lock line until it can acquire the lock? – A6SE Sep 15 '19 at 13:39
  • @A6SE This is platform-dependent - as per [the documentation](https://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileLock.html), "*A file lock is either exclusive or shared. A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks. An exclusive lock prevents other programs from acquiring an overlapping lock of either type. Once it is released, a lock has no further effect on the locks that may be acquired by other programs.*" – Alexandre Dupriez Sep 15 '19 at 13:49