Locking Files using Java

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.

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.

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.

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

With this code, I am able to use a local Linux file for locking. However, I need to be able to use a shared file resource so that multiple machines can participate in the locking. The mounted directory references a Windows share, via cifs. In this directory, the file gets created, but the fileChannel.tryLock() call generates “java.io.IOException: Invalid argument”.

About Us

Javabeat.net is a blog dedicated to Java/J2EE developers. This site focus on beginners and advanced developers. We constantly write fresh content on J2EE topics like Spring, Hibernate and wide variety of J2EE frameworks.