Java - Release a file lock

Introduction

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.

Demo

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class Main {
  public static void main(String[] args) throws Exception {
    RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
    FileChannel fileChannel = raf.getChannel();
    FileLock lock = null;/*from w w w .  jav a 2s.  c o m*/
    try {
      lock = fileChannel.lock(0, 10, true);

      /* Work with the file here */
    } catch (IOException e) {
      // Handle the exception
    } finally {
      if (lock != null) {
        try {
          lock.release();
        } catch (IOException e) {
          // Handle the exception
        }
      }
    }
  }
}

Related Topic