Java Reference
In-Depth Information
if(inLock == null)
// Cause the thread to sleep for a while before retrying the lock...
else
// We have the lock so break out of the loop...
If inLock is null , we try to acquire the lock again with the following code:
if(++tryLockCount <100) {
try {
Thread.sleep(200); // Wait for 200 milliseconds
} catch(InterruptedException e) {
e.printStackTrace(System.err);
}
continue; // Continue with next loop iteration
} else {
System.out.println("Failed to acquire lock after "+tryLockCount+" tries."
+ " Terminating...");
System.exit(1);
}
If we have tried fewer than 100 times to acquire the lock, we have another go after sending the current
thread to sleep for 200 milliseconds. Once we have failed to acquire a lock 100 times, we abandon
reading the file and exit the program.
Once we have acquired a lock, we read the file in the usual way and release the lock:
if(inChannel.read(buf) == -1)
break;
inLock.release();
System.out.println("Released file lock.");
By releasing the lock immediately after reading the file, we 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, we
won't call the release() method for the FileLock object here because we exit the outer loop.
However, after exiting the outer while loop we close the file stream and the channel, and closing the
channel will release the lock.
Summary
In this chapter, we have discussed the various ways in which we can read basic types of data from a file.
The important points we have discussed include:
You can read a file using a FileChannel object obtained from a FileInputStream object
or from a RandomAccessFile object.
You can use a channel obtained from a RandomAccessFile object that was created with
mode "rw" to both read and write the file.
Search WWH ::




Custom Search