Java Reference
In-Depth Information
System.out.println("\nAcquired file lock.");
break;
}
}
}
// Now read the file
if(inChannel.read(buf) == -1)
break;
inLock.release();
System.out.println("Released file lock.");
LongBuffer longBuf = ((ByteBuffer)(buf.flip())).asLongBuffer();
primesRead = longBuf.remaining();
longBuf.get(primes,0, longBuf.remaining());
StringBuffer str = null;
for(int i = 0 ; i< primesRead ; i++) {
if(i%6 == 0)
System.out.println();
str = new StringBuffer(" ").append(primes[i]);
System.out.print(str.substring(str.length()-12));
}
buf.clear(); // Clear the buffer for the next read
}
System.out.println("\nEOF reached.");
inFile.close(); // Close the file and the channel
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
System.exit(0);
}
}
This will output primes from the file the same as the ReadPrimes example does, but interspersed with
comments showing where we acquire and release the file lock.
How It Works
The overall while loop for reading the file is now indefinite since we need to obtain a file lock before
reading the file. We attempt to acquire the file lock in the inner while loop with the statement:
inLock = inChannel.tryLock(inChannel.position(), buf.remaining(), false);
This requests an exclusive lock on buf.remaining() bytes in the file starting with the byte at the
current file position. Acquiring a lock on just the part of the file that we want to read ensures that other
programs are not prevented from accessing the rest of the file. We have to test the value returned by the
tryLock() method for null to determine whether we have obtained a lock or not. The if statement
that does this looks quite complex, but its overall operation is quite simple:
Search WWH ::




Custom Search