Open In App

How to Implement File Locking in Java to Prevent Concurrent Access ?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, Concurrent file access may cause corruption and errors in the data. File locking is used to stop many threads or processes from concurrently accessing the same file. A simple method for implementing file locking in Java is the FileLock class, which comes under java.nio.channels package.

The Java FileLock Class provides file locking. It permits the locking of a portion of a file to stop concurrent modifications by other threads or processes.

Modes to Purchase FileLock

We can purchase the FileLock in two modes.

  • Exclusive Lock mode: We can get this lock by calling FileChannel class, lock(), tryLock().
  • Shared Lock mode: It is also called readLocks.

In this article, we will learn how to implement file locking in Java to prevent concurrent access.

Program to implement File Locking in Java

Below is the Program to implement File Locking using FileOutputStream and FileChannel:

Java




// Java Program to implement File Locking
// To Prevent Concurrent Access
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
  
// Driver Class
public class FileLockExample {
       // Main Function
     public static void main(String[] args) {
        String filePath = "gfg.txt";
  
        // Acquiring file lock in exclusive mode
        try (FileOutputStream fileOutputStream = new FileOutputStream(filePath);
             FileChannel fileChannel = fileOutputStream.getChannel();
             FileLock fileLock = fileChannel.lock()) {
  
            // Perform operations within the locked region
            System.out.println("File locked successfully!");
  
            // Simulating a process that holds the lock for some time
            Thread.sleep(500);
  
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
  
        // File lock released automatically when
        // the try-with-resources block is exited
        System.out.println("File lock released!");
    }
}


Output

File locked successfully!
File lock released!


Example of the Above Program:

  • We have specified the file path in the filePath variable.
  • Inside the try-with-resources block, we have created a FileOutputStream to the specified file path.
  • From the FileOutputStream, we obtain a FileChannel object using the getChannel() method.
  • Then acquire an exclusive file lock using the lock() method of the FileChannel object. This lock prevents other processes from accessing the file concurrently.
  • Inside the locked region, we perform operations on the file.
  • In this example, we simply print a message and simulate a process holding the lock for some time using Thread.sleep().
  • When the try-with-resources block is exited, the file lock is automatically released.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads