FileLock

Create shared file lock on file

In this example we shall show you how to create a shared file lock in Java. Creating shared 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(long, long, boolean) 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 boolean attribute marks the lock as shared or not. The method returns a handle to a FileLock class for utilizing the lock
  • Alternatively we could use the tryLock(long, long, boolean) 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 CreateSharedFileLockOnFile {
	
	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 ( block until the region can be
		    // locked, this channel is closed, or the invoking thread is interrupted)
		    FileLock lock = channel.lock(0, Long.MAX_VALUE, true);

		    // Attempts to acquire an exclusive lock on this channel's file (does not block, an
		    // invocation always returns immediately, either having acquired a lock on the requested
		    // region or having failed to do so.
		    try {
		
  lock = channel.tryLock(0, Long.MAX_VALUE, true);
		    }
		    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());
		    }

		 	// tells whether this lock is shared
		    boolean isShared = lock.isShared();
		    
		    // 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 shared file lock on a file in Java using FileChannel.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He 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