Java NIO – File Locking

Introduction to File Locking

File Locking is a mechanism by which access to a file by multiple processes can be controlled. File Locks may be mandatory or advisory. When an operating system implements advisory locking, if provides information about locks on a particular file to any process that asks for it, however it does not enforce locking. Operating systems that implement mandatory locking enforce locks and do not provide permission to a process if another process has a lock on the file. File locks are held by the jvm process and locking works only across processes and not across threads.
Files locks may be shared or exclusive. two processes wishing to read data from a file may both acquire their own shared locks. This allows both of them to read data from the file (could be same region too). An exclusive lock by a process does not allow any other process to acquire a lock on the file. The exclusive lock has to wait till the shared locks are released.

  • It needs to kept in mind that file locks are advisory in some operating systems and it would be good to treat them as such while coding.
  • It would be good to use only exclusive locks.


The example classes below show how file locking works in action. Class FileLockExampleFile1 creates a file in temporary directory and acquires an exclusive lock on it for 20 secs. Class FileLockExampleFile2 is started at the same time as FileLockExampleFile1 and waits for the lock on same file. As soon as FileLockExampleFile1 releases lock it is acquired.

Leave a Comment