FileChannel Class tryLock() Method in Java with Examples
In the case of a multi-threaded program, where multiple threads are in execution concurrently, we require locks to be acquired and released to maintain synchronization among the processes. FileChannel Class of java also provides a method known as trylock() which is used to acquire a lock on the File specified. This method is used to acquire a lock on any region of the file, specified in the parameters of the method.
A lock may be a more flexible and complicated thread synchronization mechanism than the standard synchronized block. A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, like the read lock of a ReadWriteLock.
Here the output is the object of FileLock class which mentions the lock applied, if no lock is applied (maybe due to the reason that some other processes are holding or writing the file) then this method will return null. The Position variable specifies the mark of the file from where the lock is to be acquired and the extent (up to which the lock is to be acquired) is given by the ‘size’ variable. If nothing is mentioned in the place of the second parameter then the size of Long.MAX_VALUE is taken by default. The “shared” boolean variable tells that whether the lock is shared or not. If it is false then the lock is an exclusive one otherwise shared among other processes. These are some basics of the method of synchronization. Its default value is taken to be false.
The main advantage of this method is that it will never be blocked. After the invocation, it either returns the acquired lock or returns null if the file is handled by another process or raises an exception. This method is generally different from the lock() method of the same class in the sense that in synchronization process had to wait long to get access to file or resources and acquire locks, but this method will never wait in turn it will return the null or exception.
Syntax: Method declaration
public abstract FileLock tryLock(long position, long size, boolean shared) throws IOException
Example
Java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class GFG extends Thread {
String input
= "geeks for geeks is a learning portal for computer sciences." ;
ByteBuffer buf = ByteBuffer.wrap(input.getBytes());
String fp = "gfg.txt" ;
Path pt = Paths.get(fp);
public void run()
{
try {
FileChannel fc = FileChannel.open(
pt, StandardOpenOption.WRITE,
StandardOpenOption.APPEND);
System.out.println(
Thread.currentThread().getId()
+ "says:File channel is opened for writing" );
fc.tryLock(0L, Long.MAX_VALUE, false );
System.out.println(
Thread.currentThread().getId()
+ "says:acquiring lock" );
fc.write(buf);
System.out.print(Thread.currentThread().getId()
+ "says:" );
System.out.println(
"writing is done, closing the file" );
fc.close();
}
catch (Exception e) {
System.out.println(
Thread.currentThread().getId()
+ "says: Exception" + e);
}
}
public static void main(String[] args) throws Exception
{
GFG g1 = new GFG();
GFG g2 = new GFG();
g1.start();
g2.start();
}
}
|
Output:
Output Explanation:
We are creating two threads that will try to access the file and perform a write operation on it. since to maintain synchronization we are using the trylock() method. When one of the threads acquires a lock and is doing an operation on the file and then if a second thread calls the lock to be acquired then an exception is raised by the method as the file is not free to be acquired. In the above code, we had acquired lock explicitly on the whole file. If desired we can change the size of the portion of the file on which the lock has to be acquired.
Last Updated :
13 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...