File Locking can be achieved in java by making use of the New I/O API (nio). Before the advent of New I/O API, there was no direct support in Java for locking a file. It is important to understand that File locking is hugely dependent on the native operating system on which the program is executing.
also read:
- Java Tutorials
- Java EE Tutorials
- Design Patterns Tutorials
- Java File IO Tutorials
File Locks can either be exclusive or shared. An exclusive lock can be acquired on a file only if there are no processes or applications accessing the file. It is possible for one or more processes to have any number of locks on the same file but in different region of a file in the case of a shared lock. Some operating systems doesn’t support the concept of shared locking.
Java provides lock()
and tryLock()
methods in FileChannel
class for getting a lock over the file object. Whether the lock is an exclusive lock or a shared lock depends on the flavor of the methods taking arguments which represents the region of the file to be locked. The method lock()
blocks execution until it gets a lock whereas the method tryLock()
doesn’t block and returns immediately. If a lock cannot be cannot be acquired on a file, then the tryLock()
method will return null.
FileLockTest.java
package tips.javabeat.nio.lock; import java.io.*; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; public class FileLockTest { public static void main(String[] args) throws Exception { RandomAccessFile file = null; FileLock fileLock = null; try { file = new RandomAccessFile("FileToBeLocked", "rw"); FileChannel fileChannel = file.getChannel(); fileLock = fileChannel.tryLock(); if (fileLock != null){ System.out.println("File is locked"); accessTheLockedFile(); } }finally{ if (fileLock != null){ fileLock.release(); } } } static void accessTheLockedFile(){ try{ FileInputStream input = new FileInputStream("FileToBeLocked"); int data = input.read(); System.out.println(data); }catch (Exception exception){ exception.printStackTrace(); } } }
The above program tries to lock a file called “FileToBeLocked” by calling the lock()
method on the associated File Channel object. The lock()
method blocks the thread until it gets a lock on the file. Then, in order to ensure that the file is locked, the method accessTheLockedFile()
is called which tries to read the file contents. Since the lock acquired is an exclusive lock, an IOException is thrown.