Java Reference
In-Depth Information
Note that we have not needed to execute any channel read() operations. The file contents are
available directly through the buffer.
Next we change the value at the position we retrieved the value from to store in primes[i] :
buf.putLong(index, REPLACEMENT );
This will change the contents of the buffer and this change will subsequently be written to the file at
some point. When this occurs depends on the underlying operating system.
Finally we output the contents of the primes array. We have been able to access and modify the
contents of the file without having to execute any explicit I/O operations on the file. This is potentially
much faster than using explicit read and write operations. How much faster depends on how your
operating system handles memory-mapped files.
There is one risky aspect to memory-mapped files that we need to consider.
Locking a File
You need to take care that an external program does not modify a memory-mapped file, especially if
the file could be truncated externally while you are accessing it. If you try to access a part of the file
through a MappedByteBuffer that has become inaccessible because a segment has been chopped off
the end of the file, then the results are somewhat unpredictable. You may get a junk value back that
your program may not recognize as such, or an exception of some kind may be thrown. You can
acquire a lock on the file to prevent this sort of problem. A file lock simply ensures your right of access
to the file and may also inhibit the ability of others to access the file as long as your lock is in effect.
This facility will only be available if the underlying operating system supports file locking.
A lock on a file is encapsulated by an object of the FileLock class that is defined in the
java.nio.channels package. The lock() method for a FileChannel object tries to obtain an
exclusive lock on the channel's file. Acquiring an exclusive lock on a file ensures that another program
cannot access the file. Here's one way to obtain an exclusive lock on a file:
FileLock ioFileLock = null;
try {
ioFileLock = ioChannel.lock();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
Search WWH ::




Custom Search