Java Reference
In-Depth Information
writing, and this doesn't apply here. Acquiring a shared lock on just the part of the file that you want to
read ensures that other programs are not prevented from accessing the file, but the bit you are working
with cannot be changed externally. Another program cannot acquire an exclusive overlapping lock, but it
can acquire a shared overlapping lock.
You have to test the value returned by the
tryLock()
method for
null
to determine whether you have
obtained a lock or not. The
if
statement that does this is quite simple:
if(inLock != null) { // If you have a lock
System.out.println("\nAcquired file lock.");
break; // exit the loop
}
If
inLock
is not
null
, you have a lock on the file, so you exit the loop to acquire the lock. If
inLock
is
null
, you then check how often you have tried to acquire a lock and failed:
if(++tryLockCount >= 100) { // If you've tried too often
System.out.printf("Failed to acquire lock after %d tries.
" +
"Terminating...%n",
tryLockCount);
System.exit(1); // end the program
}
The only reason for the
String
concatenation here is that the string won't fit in the width of the page.
If you have already tried 100 times to obtain a lock, you give up and exit the program. If it's fewer tries
than this, you're prepared to give it another try, but first you pause the current thread:
try {
Thread.sleep(200); // Wait for 200 milliseconds
} catch(InterruptedException e) {
e.printStackTrace();
}
This pauses the current thread for 200 milliseconds, which provides an opportunity for the program that
has an exclusive lock on the file to release it. After returning from the
sleep()
method, the
while
loop
continues for another try at acquiring a lock.
After you have acquired a lock, you read the file in the usual way and release the lock:
if(inCh.read(buf) == -1) {
break;
}
inLock.release(); // Release lock as read is
finished
System.out.println("Released file lock.");
By releasing the lock immediately after reading the file, you ensure that the amount of time the file is
blocked is a minimum. Of course, if the
read()
method returns −1 because EOF has been reached, you
won't call the
release()
method for the
FileLock
object here because you exit the outer loop. However,
after exiting the outer
while
loop you exit the
try
block, which closes the channel, and closing the chan-
nel releases the lock.