Open In App

FileChannel Class tryLock() Method in Java with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

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




// Java Program to illustrate FileChannel Class
// tryLock() method
 
// Importing libraries
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;
 
// save the file named as GFG.java
public class GFG extends Thread {
   
    // content to be written in the file.
    String input
        = "geeks for geeks is a learning portal for computer sciences.";
   
    ByteBuffer buf = ByteBuffer.wrap(input.getBytes());
   
    // path of the file
    String fp = "gfg.txt";
   
      // file channel class object
    Path pt = Paths.get(fp);
 
    public void run()
    {
        try {
           
            // the thread says if file is opened.
            FileChannel fc = FileChannel.open(
                pt, StandardOpenOption.WRITE,
                StandardOpenOption.APPEND);
            System.out.println(
                Thread.currentThread().getId()
                + "says:File channel is opened for writing");
           
            // trying lock
            fc.tryLock(0L, Long.MAX_VALUE, false);
            System.out.println(
                Thread.currentThread().getId()
                + "says:acquiring lock");
 
            // writing
            fc.write(buf);
            // release the Lock after writing
            System.out.print(Thread.currentThread().getId()
                             + "says:");
            System.out.println(
                "writing is done, closing the file");
 
            // Closing the file connections
            fc.close();
        }
 
        // Catch block to handle the exception
        catch (Exception e) {
            // Getting and printing current threads
            System.out.println(
                Thread.currentThread().getId()
                + "says: Exception" + e);
        }
 
        // Here, one file raises exception since the file
        // is being written by another thread.
    }
 
    // Main driver method
    public static void main(String[] args) throws Exception
    {
 
        // Creating an object in the main() method
        GFG g1 = new GFG();
        GFG g2 = new GFG();
 
        // Calling start() methods over the objects
        g1.start();
        g2.start();
 
        // Here Two thread in concurrency
        // are trying to access the file
    }
}


 

 

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
Previous
Next
Share your thoughts in the comments
Similar Reads