FileLock

Create file lock on file

This is an example of how to create a file lock in Java. Creating file locks using Java NIO Channels implies that you 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() 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 method returns a handle to a FileLock class for utilizing the lock
  • Alternatively we could use the tryLock() 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.

as described in the code snippet below.

 
Do not forget to close the channel after you are done processing the file so as to release operating system resources.

package com.javacodegeeks.snippets.core;

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;

public class CreateFileLockOnFile {
	
	public static void main(String[] args) {
		
		try {
			
		    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 (blocks until lock can be retrieved)
		    FileLock lock = channel.lock();

		    // Attempts to acquire an exclusive lock on this channel's file (returns null or throws
		    // an exception if the file is already locked.
		    try {
		
  lock = channel.tryLock();
		    }
		    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());
		    }

		    // release the lock
		    lock.release();

		    // close the channel
		    channel.close();
		    
		}
		catch (IOException e) {
			System.out.println("I/O Error: " + e.getMessage());
		}
		
	}

}

This was an example of how to create a file lock on a file in Java using FileChannel.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button