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
LinkedBlockingDeque in Java with Examples The LinkedBlockingDeque class in Java is a part of the Java Collection Framework. It was introduced in JDK 1.6 and it belongs to java.util.concurrent package. It is a Deque(Doubly Ended Queue) which blocks a thread if that thread tries to take elements out of it while the Deque is empty. It implemen
14 min read
LinkedBlockingQueue put() method in Java with Examples The put(E e) method of LinkedBlockingQueue inserts element passed as parameter to method at the tail of this LinkedBlockingQueue, if queue is not full. If the queue is full, then this method will wait for space to become available and after space is available, it inserts the element to LinkedBlockin
3 min read
LinkedBlockingDeque addAll() method in Java with Examples The addAll() method of LinkedBlockingDeque appends all of the elements of the specified collection to the end of this deque.Syntax: public void addAll(Collection<E> c) Parameters: This method accepts a mandatory parameter c which is the collection to be inserted in the end of the LinkedBlockin
2 min read
LinkedBlockingDeque removeIf() method in Java with Examples The removeIf() method of LinkedBlockingDeque removes the element from this LinkedBlockingDeque that satisfies the specified condition. Syntax: public boolean removeIf (Predicate<? super E> filter) Parameters: This method accepts a mandatory parameter filter which is the predicate value based o
2 min read
LinkedBlockingDeque equals() method in Java with Example The equals() method of java.util.LinkedBlockingDeque class is used to compare the specified object with this LinkedBlockingDeque for equality. Returns true if and only if the specified object is also a LinkedBlockingDeque, both LinkedBlockingDeques have the same size, and all corresponding pairs of
2 min read
Collections synchronizedCollection() method in Java with Examples The synchronizedCollection() method of java.util.Collections class is used to return a synchronized (thread-safe) collection backed by the specified collection. In order to guarantee serial access, it is critical that all access to the backing collection is accomplished through the returned collecti
2 min read
BlockingDeque removeLastOccurrence() method in Java with Examples The removeLastOccurrence() method of BlockingDeque removes the last occurrence of the specified element from this deque. If the deque does not contain the element, it remains unchanged. It returns true if this deque contained the specified element, else it returns false. Syntax: public boolean remov
2 min read
BlockingDeque removeFirstOccurrence() method in Java with Examples The removeFirstOccurrence() method of BlockingDeque removes the first occurrence of the specified element from this deque. If the deque does not contain the element, it remains unchanged. It returns true if this deque contained the specified element, else it returns false. Syntax: public boolean rem
2 min read
Types of Exception in Java with Examples Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions. Built-in Exceptions: Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situati
8 min read
BlockingDeque remove() method in Java with Examples The remove() method of BlockingDeque removes the head of the Deque container. The method throws a NoSuchElementException if the Deque container is empty. If an element in passed in the parameter, it removes the given element if present in the Deque. Syntax: public E remove() or boolean remove(elemen
2 min read