Creating a Shared File Lock on a File - Java File Path IO

Java examples for File Path IO:File Lock

Description

Creating a Shared File Lock on a File

Demo Code

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;

public class Main {
  void m() throws Exception {
    File file = new File("filename");
    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

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

    try {/*  www  . j a  va  2 s  . co m*/
      lock = channel.tryLock(0, Long.MAX_VALUE, true);
    } catch (OverlappingFileLockException e) {
      // File is already locked in this thread or virtual machine
    }

    // Determine the type of the lock
    boolean isShared = lock.isShared();

    // Release the lock
    lock.release();

    // Close the file
    channel.close();
  }
}

Related Tutorials