Search code examples
javaniofile-lockingfilelock

How safe is it to use Java FileLock?


How safe is it to use java.nio.channels.FileLock for locking files among processes? It is stated that other processes can not access the file if we have an exclusive lock. However, the below answer on another SO question states other processes have to check for the filelock too in order for our process to be safe.

(a) Are you aware that locking the file won't keep other processes from touching it unless they also use locks?

So I tested my code and tried to change, a file which I have the lock already, with Windows Text Editor and I was safe from harm but not when I test with Notepad++..

Is there a solution for locking a file appropriately in Java 6?


Solution

  • Java FileLock uses advisory (not mandatory) locks on many platforms. That means it may only provide locking against other applications that also use FileLock (or the equivalent in other languages).

    Neither Linux or Windows implement mandatory locking across the board. For instance:

    • For Linux and similar, file locking is advisory only.

    • For Windows, according to Wikipedia:

      "For applications that use the file read/write APIs in Windows, byte-range locks are enforced .... by the file systems that execute within Windows. For applications that use the file mapping APIs in Windows, byte-range locks are not enforced ..."

      In other words, locking on Windows can be either mandatory or advisory, depending on which API an Windows application uses to access files.


    How safe is it to use Java FileLock?

    If you are actually asking if it is safe to assume that FileLock provides mandatory file locking with respect to all other applications (Java & non-Java) irrespective of how they are written, the answer is No. It is NOT safe to make that assumption.


    Is there a solution for locking a file appropriately in Java 6?

    Only if all of the applications (Java & other) cooperate; e.g. by using FileLock or the equivalent.

    If you can't make that assumption, there is no solution using portable Java. Indeed, on most (if not all) common OS platforms, there is no solution at all, AFAIK ... because the platform itself doesn't support mandatory file locking independent of the application.