Open In App

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

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.

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 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:


Article Tags :