Locking Files using Java

File Locking can be achieved in java by making use of the New I/O API (nio). Before the advent of New I/O API, there was no direct support in Java for locking a file. It is important to understand that File locking is hugely dependent on the native operating system on which the program is executing.

also read:

File Locks can either be exclusive or shared. An exclusive lock can be acquired on a file only if there are no processes or applications accessing the file. It is possible for one or more processes to have any number of locks on the same file but in different region of a file in the case of a shared lock. Some operating systems doesn’t support the concept of shared locking.

Java provides lock() and tryLock() methods in FileChannel class for getting a lock over the file object. Whether the lock is an exclusive lock or a shared lock depends on the flavor of the methods taking arguments which represents the region of the file to be locked. The method lock() blocks execution until it gets a lock whereas the method tryLock() doesn’t block and returns immediately. If a lock cannot be cannot be acquired on a file, then the tryLock() method will return null.


package tips.javabeat.nio.lock;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class FileLockTest {

    public static void main(String[] args) throws Exception {

        RandomAccessFile file = null;
        FileLock fileLock = null;
            file = new RandomAccessFile("FileToBeLocked", "rw");
            FileChannel fileChannel = file.getChannel();

            fileLock = fileChannel.tryLock();
            if (fileLock != null){
                System.out.println("File is locked");
            if (fileLock != null){

    static void accessTheLockedFile(){

            FileInputStream input = new FileInputStream("FileToBeLocked");
            int data = input.read();
        }catch (Exception exception){

The above program tries to lock a file called “FileToBeLocked” by calling the lock() method on the associated File Channel object. The lock() method blocks the thread until it gets a lock on the file. Then, in order to ensure that the file is locked, the method accessTheLockedFile() is called which tries to read the file contents. Since the lock acquired is an exclusive lock, an IOException is thrown.



About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

  • Pingback: What is transient keyword in Java?()

  • Paul Price

    With this code, I am able to use a local Linux file for locking. However, I need to be able to use a shared file resource so that multiple machines can participate in the locking. The mounted directory references a Windows share, via cifs. In this directory, the file gets created, but the fileChannel.tryLock() call generates “java.io.IOException: Invalid argument”.

    Here is the mount from /etc/fstab:
    //machineABC/topDir/secondDir/thirdDir /SharedFiles cifs credentials=/root/Mounts.cred,domain=MYDOMAIN,file_mode=0755,dir_mode=0755,uid=myUser,gid=myGroup 1 2