Java Reference
In-Depth Information
Because the MappedByteBuffer class is a subclass of the ByteBuffer class, you have all the
ByteBuffer methods available for a MappedByteBuffer object. This implies that you can create view buf-
fers for a MappedByteBuffer object, for instance.
The MappedByteBuffer class defines three methods of its own to add to those inherited from the
ByteBuffer class:
TABLE 11-1: MappedByteBuffer Class Methods
METHOD DESCRIPTION
force() If the buffer was mapped in MapMode.READ_WRITE mode, this method forces any changes that you make
to the buffer's contents to be written to the file and returns a reference to the buffer. For buffers created
with other access modes, this method has no effect.
load() Tries on a “best efforts” basis to load the contents of the buffer into memory and returns a reference to the
buffer.
isLoaded() Returns true if it is likely that this buffer's contents are available in physical memory and false other-
wise.
The load() method is dependent on external operating system functions executing to achieve the desired
result, so the result cannot in general be guaranteed. Similarly, when you get a true return from the
isLoaded() method, this is an indication of a probable state of affairs rather than a guarantee. This doesn't
imply any kind of problem. It just means that accessing the data in the mapped byte buffer may take longer
that you might expect in some instances.
Unless the file is large, using a mapped byte buffer is typically slower than using the read() and write()
methods for a channel. Using a memory-mapped file through a MappedByteBuffer is simplicity itself
though, so let's try it.
TRY IT OUT: Using a Memory-Mapped File
You will access and modify the primes_backup.bin file using a MappedByteBuffer , so you might want
to rerun the file copy program to restore it to its original condition. Here's the code:
import static java.nio.file.StandardOpenOption.*;
import static java.nio.channels.FileChannel.MapMode.READ_WRITE;
import java.nio.file.*;
import java.nio.channels.FileChannel;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.util.EnumSet;
public class MemoryMappedFile {
public static void main(String[] args) {
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java
Stuff").resolve("primes_backup.bin");
if(!Files.exists(file)) {
System.out.println(file + " does not exist. Terminating
Search WWH ::




Custom Search