• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us

Locking Files using Java

October 26, 2007 //  by Krishna Srinivasan

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.

Category: JavaTag: File IO

About Krishna Srinivasan

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.

Previous Post: « Apache POI – Reading Excel sheet using Java
Next Post: Customizing Dragging and Dropping for Swing Components »

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

How to Initialize an Array in Java

Introduction to Java Server Faces (JSF)

Introduction to Java 6.0 New Features, Part–1

Java 6.0 Features Part – 2 : Pluggable Annotation Processing API

Introduction to Java Server Faces(JSF) HTML Tags

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact