Java FileChannel.lock(long position, long size, boolean shared)

Syntax

FileChannel.lock(long position, long size, boolean shared) has the following syntax.

public abstract FileLock lock(long position,  long size,  boolean shared)   throws IOException

Example

In the following code shows how to use FileChannel.lock(long position, long size, boolean shared) method.


import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
/*w  w  w .ja  v  a 2s . c o  m*/
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");
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    java.nio.channels »




FileChannel