Java Reference
In-Depth Information
// Get an exclusive lock on first 10 bytes
FileLock lock = fileChannel.lock(0, 10, false);
// Try to get an exclusive lock on the entire file
FileLock lock = fileChannel.tryLock();
if (lock == null) {
// Could not get the lock
}
else {
// Got the lock
}
// Try to lock 100 bytes starting from the 11th byte in a shared mode
FileLock lock = fileChannel.tryLock(11, 100, true);
if (lock == null) {
// Could not get the lock
}
else {
// Got the lock
}
The file region that you lock may not be contained in the range of the file size. Suppose you have a file with a size
of 100 bytes. When you request a lock on this file, you can specify that you want to lock a region of this file starting at
byte 11 and covering 5000 bytes. Note that this file contains only 100 bytes; you are locking 5000 bytes. In such a case,
if the file size grows beyond 100 bytes, your lock covers the additional region of the file. Suppose you locked 0 to
100 bytes of a 100-byte file. If this file grows to 150 bytes, your lock does not cover the last 50 bytes that was added
after you acquired the lock. The lock() and tryLock() methods of the FileChannel object, where you do not
specify any argument, lock a region from 0 to Long.MAX_VALUE of the file. The two method calls fc.lock() and
fc.lock(0, Long.MAX_VALUE, false) have the same effect.
When you are done with the file lock, you need to release it by using the release() method. A file lock is released
in three ways: by calling its release() method, by closing the file channel it is obtained from, and by shutting down
the JVM. It is good practice to use a try-catch-finally block to acquire and release a file lock as follows:
RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
FileChannel fileChannel = raf.getChannel();
FileLock lock = null;
try {
lock = fileChannel.lock(0, 10, true);
/* Work with the file here */
}
catch(IOException e) {
// Handle the exception
}
finally {
if (lock != null) {
try {
lock.release();
}
 
Search WWH ::




Custom Search