FileChannel lock

In this chapter you will learn:

  1. How to lock a FileChannel
  2. Attempts to acquire an exclusive lock on this channel's file

Lock a FileChannel

  • FileLock lock() Acquires an exclusive lock on this channel's file.
  • abstract FileLock lock(long position, long size, boolean shared) Acquires a lock on the given region of this channel's file.
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
//  j  av  a2 s . c om
public class Main {
  public static void main(String[] argv) throws Exception {
    String filename = "test.dat";

    RandomAccessFile raf1 = new RandomAccessFile(filename, "rw");
    FileChannel fc1 = raf1.getChannel();

    RandomAccessFile raf2 = new RandomAccessFile(filename, "rw");
    FileChannel fc2 = raf2.getChannel();

    System.out.println("Grabbing first lock");
    FileLock lock1 = fc1.lock(0L, Integer.MAX_VALUE, false);

    System.out.println("Grabbing second lock");
    FileLock lock2 = fc2.lock(5, 10, false);

    System.out.println("Exiting");
  }
}

Attempts to acquire an exclusive lock on this channel's file

FileLock tryLock() Attempts to acquire an exclusive lock on this channel's file.

import java.io.FileOutputStream;
import java.nio.channels.FileLock;
/*from  ja v a  2s.  c  o m*/
public class Main {
  public static void main(String[] args) throws Exception {
    FileOutputStream fos = new FileOutputStream("file.txt");
    FileLock fl = fos.getChannel().tryLock();
    if (fl != null) {
      System.out.println("Locked File");
      Thread.sleep(100);
      fl.release();
      System.out.println("Released Lock");
    }
    fos.close();
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to map FileChannel to memory
  2. How to read content from FileChannel to a ByteBuffer
  3. Transfers bytes into channel's file from the given readable byte channel
Home » Java Tutorial » NIO
NIO
FileChannel
FileChannel position
FileChannel lock
FileChannel read
FileChannel write