Java Reference
In-Depth Information
// Wait 200 msec before the next try for a file lock
try {
Thread.sleep(200); // Wait for 200 milliseconds
} catch(InterruptedException e) {
e.printStackTrace();
}
}
// You have a lock so now read the file
if(inCh.read(buf) == -1) {
break;
}
inLock.release();
// Release lock as read is
finished
System.out.println("Released file lock.");
LongBuffer longBuf =
((ByteBuffer)(buf.flip())).asLongBuffer();
primesRead = longBuf.remaining();
longBuf.get(primes,0, longBuf.remaining());
for(int i = 0 ; i < primesRead ; ++i) {
if(i%6 == 0) {
System.out.println();
}
System.out.printf("%12d", primes[i]);
}
buf.clear();
// Clear the buffer for the
next read
}
System.out.println("\nEOF reached.");
} catch(IOException e) {
e.printStackTrace();
}
}
}
LockingPrimesRead.java
This outputs primes from the file just as the
ReadPrimes
example does, but interspersed with comments
showing where you acquire and release the file lock.
How It Works
The overall
while
loop for reading the file is now indefinite because you need to obtain a file lock before
reading the file. You attempt to acquire the file lock in the inner
while
loop with the following statement:
inLock = inCh.tryLock(inCh.position(), buf.remaining(),
true);
This requests a shared lock on
buf.remaining()
bytes in the file starting with the byte at the current
file position. You can't get an exclusive lock on a file unless it has been opened for both reading and