Home  >  Core Java

Example of FileLock in Java NIO Channels

By Arvind Rai, November 20, 2013
FileLock belongs to the package java.nio.channels and is available in java from JDK 1.4. FileLock locks or tries for lock for the given part of the file. Locking files is done either in shared mode or non-shared mode. FileLock has two important method FileLock.lock() and FileLock.tryLock(). FileLock.lock(long position, long size, boolean shared) and FileLock.tryLock(long position, long size, boolean shared) take arguments as initial position and file size to lock and one more parameter to decide whether the lock is shared or not.

Difference between FileLock.lock() and FileLock.tryLock()

FileLock.lock waits for locks for the given file if already locked whereas FileLock.tryLock does not wait for lock and it returns null if unable to acquire lock.

FileLockTest.java
package com.concretepage.nio.channels;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class FileLockTest {
    public static void main(String[] args) throws IOException {
        
          FileInputStream fin = null;
          FileChannel fchannel = null;
          //opens a file to read from the given location
          fin = new FileInputStream("C:/temp/test.txt");
          
          //returns FileChannel instance to read the file
          fchannel = fin.getChannel();   
          
          //gets lock from postion 10 to 100
          FileLock lock1 = fchannel.lock(10,100, true); 
          System.out.println(lock1.isShared());
           
          //try for lock from position 201 to Integer.MAX_VALUE
          FileLock lock2 = fchannel.tryLock(201,Long.MAX_VALUE, false); 
          System.out.println(lock2.isShared());
          
          //locks are released.
          lock1.release();
          lock2.release();
          
          fchannel.close();
     }
}
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us