FileChannel: lock(long position, long size, boolean shared)

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;

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");
  }
}
Home 
  Java Book 
    File Stream  

FileChannel:
  1. FileChannel
  2. FileChannel.MapMode.READ_WRITE
  3. FileChannel: close()
  4. FileChannel: lock(long position, long size, boolean shared)
  5. FileChannel: map(MapMode mode, long position, long size)
  6. FileChannel: position()
  7. FileChannel: position(long newPosition)
  8. FileChannel: read(ByteBuffer dst)
  9. FileChannel: size()
  10. FileChannel: transferFrom(ReadableByteChannel src, long position, long count)
  11. FileChannel: transferTo(long position, long count, WritableByteChannel target)
  12. FileChannel: tryLock()
  13. FileChannel: write(MappedByteBuffer buffer)