Java - File Input Output File Lock

Introduction

Java supports file locking to synchronize access to a file.

You can lock a region of a file or the entire file.

The file lock is operating system dependant.

There are two kinds of file locking: exclusive and shared.

Only one program can hold an exclusive lock on a region of a file.

Multiple programs can hold shared locks on the same region of a file.

You cannot mix an exclusive lock and a shared lock on the same region of a file.

API

FileLock class in the java.nio.channels package represents a file lock.

You acquire a lock on a file by using the lock() or tryLock() method of the FileChannel object.

The lock() method blocks if the lock on the requested region of the file is not available.

The tryLock() method does not block; it returns immediately.

It returns an object of the FileLock class if the lock was acquired; otherwise, it returns null.

The version without an argument locks the entire file.

The version with three arguments accepts the starting position of the region, the number of bytes, and a boolean flag to indicate if the lock is shared.

The isShared() method returns true if the lock is shared; otherwise, it returns false.

The following code shows different ways of obtaining locks on a file.

Demo

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

public class Main {
  public static void main(String[] args) throws Exception {
    // Create a random access file and obtain a channel for it
    RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
    FileChannel fileChannel = raf.getChannel();

    // Get an exclusive lock on the file
    FileLock lock = fileChannel.lock();
    // Get an exclusive lock on first 10 bytes
    // FileLock lock = fileChannel.lock(0, 10, false);

    // Try to get an exclusive lock on the entire file
    // FileLock lock = fileChannel.tryLock();
    if (lock == null) {
      // Could not get the lock
    } else {//from w  w w.  j  a va 2  s.c om
      // Got the lock
    }

    // Try to lock 100 bytes starting from the 11th byte in a shared mode
    // FileLock lock = fileChannel.tryLock(11, 100, true);
    if (lock == null) {
      // Could not get the lock
    } else {
      // Got the lock
    }
  }
}

Related Topics