OverlappingFileLockException in Java with Examples
Last Updated :
30 Sep, 2021
An OverlappingFileLockException is thrown when attempting to acquire a lock that overlaps an existing or pending lock held by this process.
This exception is thrown by the lock( ) and tryLock( ) methods of FileChannel if the requested lock region overlaps a file lock that is already held by some thread in this JVM, or if there is already a thread in this JVM waiting to lock an overlapping region of the same file. The FileChannel file locking mechanism is designed to lock files against concurrent access by two separate processes. Two threads within the same JVM should not attempt to acquire a lock on overlapping regions of the same file, and any attempt to do so causes an exception of this type to be thrown.
Package View
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IllegalStateException
java.nio.channels.OverlappingFileLockException
Remember: It does implement Serializable interface.
Syntax:
public class OverlappingFileLockException
extends IllegalStateException
Note: An unchecked exception is thrown when an attempt is made to acquire a lock on a region of a file that overlaps a region already locked by the same Java virtual machine, or when another thread is already waiting to lock an overlapping region of the same file.
Constructor Summary
- OverlappingFileLockException(): Constructs an instance of this class.
Implementation:
In this example, we shall show you how to create a shared file lock in Java and handle OverlappingFileLockException. Creating shared file locks using Java NIO Channels implies that one should :
- Create a File object to encapsulate an actual file in the file system that you want to lock to
- Create a random access file stream (read-write). To do so you must first create a RandomAccessFile object to encapsulate the file object created above and open it for read-write operations. Then use the getChannel() API method of the RandomAccessFile object to get the file channel to read/write data from/to
- Acquire an exclusive lock on this channel’s file by using the lock(long, long, boolean) API method of the FileChannel class. This method blocks until the region can be locked or this channel is closed or the invoking thread is interrupted. The boolean attribute marks the lock as shared or not. The method returns a handle to a FileLock class for utilizing the lock
- Alternatively, we could use the tryLock(long, long, boolean) API method of the FileChannel class. This method attempts to acquire an exclusive lock on this channel’s file but does not block; an invocation always returns immediately, either having acquired a lock on the requested region or having failed to do so.
Example 1
Java
// Java Program to Illustrate Shared lock over File
// Importing required classes
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
// Main class
// CreateSharedFileLockOnFile
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try {
// Creating a file
File file = new File("fileToLock.dat");
// Creates a random access file stream to read
// from, and optionally to write to
FileChannel channel
= new RandomAccessFile(file, "rw")
.getChannel();
// Acquire an exclusive lock on this channel's
// file ( block until the region can be locked,
// this channel is closed, or the invoking
// thread is interrupted)
FileLock lock
= channel.lock(0, Long.MAX_VALUE, true);
// Attempts to acquire an exclusive lock on this
// channel's file (does not block, an invocation
// always returns immediately, either having
// acquired a lock on the requested region or
// having failed to do so.
try {
lock = channel.tryLock(0, Long.MAX_VALUE,
true);
}
catch (OverlappingFileLockException e) {
// thrown when an attempt is made to acquire
// a lock on a a file that overlaps a region
// already locked by the same JVM or when
// another thread is already waiting to lock
// an overlapping region of the same file
System.out.println(
"Overlapping File Lock Error: "
+ e.getMessage());
}
// Checking whether this lock is shared
boolean isShared = lock.isShared();
// Releasing the lock
// using release() method
lock.release();
// Closing the channel
// using standard close() method
channel.close();
}
// Catch block to handle exceptions
catch (IOException e) {
// Display message(error) if I/O exception
// occurs
System.out.println("I/O Error: "
+ e.getMessage());
}
}
}
Output:
Example 2:
Java
// Java Program to Lock a File before Writing into It
// Importing required classes
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.util.concurrent.TimeUnit;
// Main class
public class Demo {
// Main driver method
public static void main(String[] args) throws Exception
{
// Creating object of RandomAccessFile
RandomAccessFile file
= new RandomAccessFile("accounts.txt", "rw");
// Similarly creating object of FileChannel class
FileChannel channel = file.getChannel();
// Initially setting lock to file as null
// as there is no lock by far
FileLock lock = null;
// Try block to check for exceptions
try {
lock = channel.tryLock();
}
// Catch block to handle exceptions
catch (final OverlappingFileLockException e) {
// Closing channel and file in order to
// free up memory resources and avoid leakage
// using close() method
file.close();
channel.close();
}
// Writing something while inlocked
file.writeChars("writing after lock");
// Making it to sleep for very small amount of time
TimeUnit.HOURS.sleep(1);
// Releasig lock over file using release() method
lock.release();
// Again closing channel and file in order to
// free up memory resources and avoid leakage
// using close() method
file.close();
channel.close();
}
}
Output:

It will throw the OverlappingFileLockException, if a lock that overlaps the requested region is already held by this Java virtual machine, or if another thread is already blocked in this method and is attempting to lock an overlapping region.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read