Java NIO - FileLock


As we know that Java NIO supports concurrency and multi threading which enables it to deal with the multiple threads operating on multiple files at same time.But in some cases we require that our file would not get share by any of thread and get non accessible.

For such requirement NIO again provides an API known as FileLock which is used to provide lock over whole file or on a part of file,so that file or its part doesn't get shared or accessible.

in order to provide or apply such lock we have to use FileChannel or AsynchronousFileChannel,which provides two methods lock() and tryLock()for this purpose.The lock provided may be of two types −

  • Exclusive Lock − An exclusive lock prevents other programs from acquiring an overlapping lock of either type.

  • Shared Lock − A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks.

Methods used for obtaining lock over file −

  • lock() − This method of FileChannel or AsynchronousFileChannel acquires an exclusive lock over a file associated with the given channel.Return type of this method is FileLock which is further used for monitoring the obtained lock.

  • lock(long position, long size, boolean shared) − This method again is the overloaded method of lock method and is used to lock a particular part of a file.

  • tryLock() − This method return a FileLock or a null if the lock could not be acquired and it attempts to acquire an explicitly exclusive lock on this channel's file.

  • tryLock(long position, long size, boolean shared) − This method attempts to acquires a lock on the given region of this channel's file which may be an exclusive or of shared type.

Methods of FileLock Class

  • acquiredBy() − This method returns the channel on whose file lock was acquired.

  • position() − This method returns the position within the file of the first byte of the locked region.A locked region need not be contained within, or even overlap, the actual underlying file, so the value returned by this method may exceed the file's current size.

  • size() − This method returns the size of the locked region in bytes.A locked region need not be contained within, or even overlap, the actual underlying file, so the value returned by this method may exceed the file's current size.

  • isShared() − This method is used to determine that whether lock is shared or not.

  • overlaps(long position,long size) − This method tells whether or not this lock overlaps the given lock range.

  • isValid() − This method tells whether or not the obtained lock is valid.A lock object remains valid until it is released or the associated file channel is closed, whichever comes first.

  • release() − Releases the obtained lock.If the lock object is valid then invoking this method releases the lock and renders the object invalid. If this lock object is invalid then invoking this method has no effect.

  • close() − This method invokes the release() method. It was added to the class so that it could be used in conjunction with the automatic resource management block construct.

Example to demonstrate file lock.

Following example create lock over a file and write content to it

package com.java.nio;
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 FileLockExample {
   public static void main(String[] args) throws IOException {
      String input = "Demo text to be written in locked mode.";  
      System.out.println("Input string to the test file is: " + input);  
      ByteBuffer buf = ByteBuffer.wrap(input.getBytes());  
      String fp = "D:file.txt";  
      Path pt = Paths.get(fp);  
      FileChannel channel = FileChannel.open(pt, StandardOpenOption.WRITE,StandardOpenOption.APPEND);  
      channel.position(channel.size() - 1); // position of a cursor at the end of file       
      FileLock lock = channel.lock();   
      System.out.println("The Lock is shared: " + lock.isShared());  
      channel.write(buf);  
      channel.close(); // Releases the Lock  
      System.out.println("Content Writing is complete. Therefore close the channel and release the lock.");  
      PrintFileCreated.print(fp);  
   }  
}

package com.java.nio;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class PrintFileCreated {
   public static void print(String path) throws IOException {  
      FileReader filereader = new FileReader(path);  
      BufferedReader bufferedreader = new BufferedReader(filereader);  
      String tr = bufferedreader.readLine();    
      System.out.println("The Content of testout.txt file is: ");  
      while (tr != null) {      
         System.out.println("    " + tr);  
         tr = bufferedreader.readLine();  
      }  
   filereader.close();  
   bufferedreader.close();  
   }  
}

Output

Input string to the test file is: Demo text to be written in locked mode.
The Lock is shared: false
Content Writing is complete. Therefore close the channel and release the lock.
The Content of testout.txt file is: 
To be or not to be?Demo text to be written in locked mode.
Advertisements