How to Implement File Locking in Java to Prevent Concurrent Access ?
Last Updated :
14 Feb, 2024
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
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class FileLockExample {
public static void main(String[] args) {
String filePath = "gfg.txt" ;
try (FileOutputStream fileOutputStream = new FileOutputStream(filePath);
FileChannel fileChannel = fileOutputStream.getChannel();
FileLock fileLock = fileChannel.lock()) {
System.out.println( "File locked successfully!" );
Thread.sleep( 500 );
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
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.
Share your thoughts in the comments
Please Login to comment...