Locking

suggest change

A file can be locked using the FileChannel API, which can be acquired from input/output streams and from RandomAccessFile.

Example with streams

// Open a file stream

FileInputStream ios = new FileInputStream(filename);

// get underlying channel
FileChannel channel = ios.getChannel();

/*
 * try to lock the file. true means whether the lock is shared or not i.e. multiple processes can acquire a
 * shared lock (for reading only) Using false with readable channel only will generate an exception. You should
 * use a writable channel (taken from FileOutputStream) when using false. tryLock will always return immediately
 */
FileLock lock = channel.tryLock(0, Long.MAX_VALUE, true);

if (lock == null) {
    System.out.println("Unable to acquire lock");
} else {
    System.out.println("Lock acquired successfully");
}

// you can also use blocking call which will block until a lock is acquired.
channel.lock();

// Once you have completed desired operations of file. release the lock
if (lock != null) {
    lock.release();
}

// close the file stream afterwards
// Example with RandomAccessFile. This repeats the name channel, so it is a separate sketch.
RandomAccessFile randomAccessFile = new RandomAccessFile(filename,  "rw");
FileChannel channel = randomAccessFile.getChannel();
//repeat the same steps as above but now you can use shared as true or false as the channel is in read write mode

tryLock(..., true) requests a shared lock, which fits a FileInputStream channel. The later channel.lock() requests an exclusive lock and ignores the FileLock it returns. On a read-only channel that call throws NonWritableChannelException. The lock from tryLock is the one release uses.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents