Reproducing my answer from here (if deleted) and adding Jeff Foster's feedback:
Given that an OverlappingFileLockException is thrown, it seems that another thread in the same process is trying to lock the same file. This is not a conflict between A and B, but rather a conflict inside B if someone follows the API documentation using the lock () method and when the condition under which it throws an OverlappingFileLockException:
If a lock that overlaps the requested region is already supported by this Java virtual machine, or if another thread in this method is already blocked, it tries to block the overlapping region of the same file
The only solution to prevent this is to prevent any other thread in B from getting a lock in the same file or the same overlap area in the file.
Throwing an IOException has a slightly more interesting message. This probably confirms the above theory, but without looking at the entire source code, I cannot confirm anything. It is expected that the lock method will be locked until an exclusive lock is received. If this was purchased, then there should be no problem reading from the file. Except for one condition. If the file has already been opened (and locked) by the same JVM in another thread using the File object (or, in other words, a second / different file descriptor), then an attempt to read the first file descriptor will fail even if the lock was acquired (at the end finally, blocking does not block other threads).
An improved design should consist in creating a single thread in each process that receives an exclusive file lock (when using one File object or one file descriptor) for only a certain amount of time, performs the required activity in the file, and then release the lock. Strike>
As Jeff noted, using the NIO API is likely to resolve the issue. This is entirely due to the ability of the FileReader API to open a new file descriptor , which is different from the one on which the lock was received.
source share