0

I have problem with file lock on Linux in Java I have two apps on different hosts(A and B) and shared folder for file lock. In A I get lock with channel.lock(). Then I call channel.tryLock() in B. It throws OverlappingFileLockException. And its ok. But then I call channel.tryLock() in A (It throws OverlappingFileLockException). After this, in B channel.tryLock() returns valid lock without any exceptions.

Did someone had same problem. Thanks

Alexey
  • 1,198
  • 1
  • 15
  • 35

1 Answers1

3

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

El Mac
  • 3,256
  • 7
  • 38
  • 58
  • I don't know what the reason for this behavior approach is, but if it is like I said, it might be a bit of a design flaw. – El Mac Mar 29 '16 at 09:50
  • Not really; file locks are a relatively low-level consstruct provided by the OS to facilitate cross-process synchronization, not intra-process synchronization. – Tassos Bassoukos Mar 29 '16 at 09:57
  • @TassosBassoukos That makes sense, I don't remember how that goes exactly. Thanks for the clarification. Can you confirm this is because of the intra-process synchronization? – El Mac Mar 29 '16 at 10:00
  • I think your answer is correct; I just wanted to clarify why this behavior exists. At least in Linux, for performance reasons by default all threads share the same file descriptor tables, thus another thread is not another program... – Tassos Bassoukos Mar 29 '16 at 12:23