From the Java Doc (method tryLock()
)
If it fails to acquire a lock because an overlapping lock is held by
another program then it returns null. If it fails to acquire a lock
for any other reason then an appropriate exception is thrown.
This means the tryLock
method will throw an OverlappingFileLockException
, if there is an other problem than an other application having the lock.
If you are multi-threaded, you should know this:
File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.
If you keep reading about that exception:
OverlappingFileLockException - If a lock that overlaps the requested
region is already held by this Java virtual machine, or if another
thread is already blocked in this method and is attempting to lock an
overlapping region of the same file
So I think your problem is that you are trying to acquire a lock from withhin the same application that already has one. You would have to check it for me, but it seems like in this case it will not return null
, but throw an Exception.
Also: The Documentation does not say anything about what happens if you try to lock the file from the same application. It always speaks about returning null
, if an other application has acquired the lock:
A lock object representing the newly-acquired lock, or null if the
lock could not be acquired because another program holds an
overlapping lock
Link to JavaDoc