Sunday, August 9, 2015

File Locking in Java

NIO supports file locking to synchronize access to a file. You have the ability to lock a region of a file or the entire file. The file locking mechanism is handled by the operating system and therefore its exact effect is platform-dependent. On some operating systems, a file lock is advisory, whereas on some, it is mandatory. Since it is handled by the operating system, its effect is visible to other programs as well as to Java programs running in other JVMs. In this article, we try to understand this concept with the help of an example.

There are two kinds of file locking:

  1. Exclusive lock  : Only one program can hold an exclusive lock on a region of a file
  2. Shared lock : Multiple programs can hold shared locks on the same region of a file

You cannot mix an exclusive lock and a shared lock on the same region of a file. If a program has a shared lock on a region, another program must wait to get an exclusive lock on that region and vice versa. Some operating systems do not support a shared file lock, and in that case, the request for a shared file lock is converted to a request for an exclusive file lock.

How to represent File Lock
An object of the FileLock class, which is in the java.nio.channels package, represents a file lock. You acquire a lock on a file by using the lock() or tryLock() method of the FileChannel object

  • The lock() method blocks if the lock on the requested region of the file is not available
  • The tryLock() method does not block; it returns immediately. It returns an object of the FileLock class if the lock was acquired; otherwise, it returns null.

Versions of lock() and tryLock() methods
Both lock() and tryLock() methods have two versions: one without an argument and another with three arguments

  • The version without an argument locks the entire file.
  • The version with three arguments accepts the starting position of the region to lock, the number of bytes to lock, and a boolean flag to indicate if the lock is shared. The isShared() method of the FileLock object returns true if the lock is shared; otherwise, it returns false.

Different ways of obtaining locks on a file
The exception handling code is omitted for readability.

The file region that you lock may not be contained in the range of the file size. Suppose you have a file with a size of 100 bytes. When you request a lock on this file, you can specify that you want to lock a region of this file starting at byte 11 and covering 5000 bytes. Note that this file contains only 100 bytes; you are locking 5000 bytes. In such a case, if the file size grows beyond 100 bytes, your lock covers the additional region of the file. Suppose you locked 0 to 100 bytes of a 100-byte file. If this file grows to 150 bytes, your lock does not cover the last 50 bytes that was added after you acquired the lock.

The lock() and tryLock() methods of the FileChannel object, where you do not specify any argument, lock a region from 0 to Long.MAX_VALUE of the file. The two method calls fc.lock() and fc.lock(0, Long.MAX_VALUE, false) have the same effect

How to release the lock
When you are done with the file lock, you need to release it by using the release() method. 
A file lock is released in three ways:
by calling its release() method, by closing the file channel it is obtained from, and by shutting down the JVM. It is good practice to use a try-catch-finally block to acquire and release a file lock as follows:

In this example, two thread will try to acquire the lock on the same file.

Sample output
File is locked by Thread-0
Thread-1 tried to acquire the lock
lock is released by Thread-0

If you know anyone who has started learning Java, why not help them out! Just share this post with them.Thanks for studying today!...


  1. Hi,

    This is siva from Hyderabad.I am working on SEO Analyst.Your site was very good.i have one Idea.I have Google Adsense Account.i think you Don't have that I will give you my Adsense Account for your Site.if you have Intrested Please Contact Me my PH NO:09553267423...........

    Siva G.


  2. I saw lot of information On Other Site But this blog helped me alot to learn Java Thanks for sharing.........

  3. There are lots of information about latest technology and how to get trained in them, like this have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies. By the way you are running a great blog. Thanks for sharing this.

    Hadoop Training in Chennai

    Base SAS Training in Chennai

  4. Very thanks to every one its too easy in to understanding thank u so much for this blog for gave valuable info to us.
    Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.
    best java training in velachery |
    java training institute in chennai

  5. A easy and exciting blog about java learning. Please comment your opinions and share..

  6. Really great post, Thank you for sharing this knowledge. Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Sales and training programs. Please keep it up.

  7. Hi
    I have read your blog its very attractive and impressive. I like it your blog.....
    java training in delhi


  8. This is a great site for the modern architecture enthusiast. Plenty of dazzling photographs and just a plain neat blog..Want to build your own website
    White Label Website Builder

  9. Thanks for sharing this information,this is useful to me...

    Core Java Online Training Hyderabad

  10. Java is one of the most important element in each and every electronic device which helps in many activities. In java we have many different concepts with efficient to all the modules File Locking concept is a bit important and essential You have given an exact crystal clear approach to File Locking, When I was doing my PMP Training in Kuwait I was supposed to handle certain Java Projects in equal to other domains also Well Thank you so much for the Blog I will be looking forward for more and more updates from you.

  11. I am technology Enthusiast. Your blog is really awesome, attractive and impressive. I like the way you think. it is very useful for Java SE & Java EE Learners. Your article adds best knowledge to our Java Online Training in India. or learn thru Java Online Training in India Students. or learn thru JavaScript Online Training in India. Appreciating the persistence you put into your blog and detailed information you provide. Kindly keep blogging.

  12. Thanks for your marvelous posting! It is very useful and good. Come on. I want to introduce an get app installs, I try it and I feel it is so good to rank app to top in app store search results, have you ever heard it?

  13. COEPD LLC - Center of Excellence for Professional Development is the most trusted online training platform to global participants. We are primarily a community of Business Analysts who have taken the initiative to facilitate professionals of IT or Non IT background with the finest quality training. Our trainings are delivered through interactive mode with illustrative scenarios, activities and case studies to help learners start a successful career. We impart knowledge keeping in view of the challenging situations individuals will face in the real time, so that they can handle their job deliverables with at most confidence.

  14. Java is very good blog,it's highly professional course.Thanks for sharing
    java online Training India

  15. Your concepts were easy to understand that I wondered why I never looked at it before. This information is definitely useful for everyone.
    You can also visit here Java training in delhi, java programming in delhi

  16. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head.
    I am highly impressed with your blog. It is very nicely explained.
    Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.

  17. Australia Best Tutor is one of the best Online Assignment Help providers at an affordable price. Here All Learners or Students are getting best quality assignment help with reference and styles formatting.

    Visit us for more Information

    Australia Best Tutor
    Sydney, NSW, Australia
    Call @ +61-730-407-305
    Live Chat @

    Our Services

    Online assignment help
    my assignment help Student
    Assignment help Student
    help with assignment Student
    Students instant assignment help
    Students Assignment help Services


  18. It is very good blog and useful for students and developer ,Thanks for sharing
    Core Java Online Training
    Java Online Course
    Java Online Training Hyderabad

  19. This concept is a good way to enhance the knowledge.thanks for sharing. please keep it up Java online training Bangalore