Example usage for java.nio.channels FileChannel lock

List of usage examples for java.nio.channels FileChannel lock

Introduction

In this page you can find the example usage for java.nio.channels FileChannel lock.

Prototype

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

Source Link

Document

Acquires a lock on the given region of this channel's file.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    File file = new File("filename");
    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

    FileLock lock = channel.lock(0, Long.MAX_VALUE, true);

    lock = channel.tryLock(0, Long.MAX_VALUE, true);

    boolean isShared = lock.isShared();

    lock.release();/*from ww  w.  ja va 2  s  .  c o  m*/

    channel.close();
}

From source file:Main.java

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  .j  a v  a2 s .c o m
    try {
        lock = fileChannel.lock(0, 10, true);

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

}

From source file:Main.java

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");
}