Java Memory-Mapped Files: FileChannel.map and Performance
Map files into memory in Java with FileChannel.map: READ_ONLY, READ_WRITE and PRIVATE modes, MappedByteBuffer access, force, byte order, measured performance against streams and RandomAccessFile, the 2 GB limit, and Java 22's MemorySegment mapping with deterministic unmapping through an Arena.
kvi5hnuCode Sprout team member9 min readOn this page
Operating systems with virtual memory can map a file, or a region of one, into a process's address space. The file's bytes then appear as ordinary memory. Reading a byte is a memory access, and the operating system pages data in from disk on demand and writes modified pages back. There's no explicit read call per chunk and no copying through intermediate buffers. For random access to large files, that can be dramatically faster than the classic APIs.
How fast is it?
The demo computes the CRC-32 checksum of a file five ways. On a 50 MB file on one test machine (a recent laptop with an SSD), the times were:
| Method | Time |
|---|---|
InputStream, one read() per byte | 15.5 s |
BufferedInputStream, one read() per byte | 0.18 s |
RandomAccessFile, one readByte() per byte | 16.4 s |
memory-mapped, one get(i) per byte | 0.13 s |
memory-mapped, CRC32.update(buffer) in bulk | 0.01 s |
Your numbers will differ, but the pattern is typical. Unbuffered byte-at-a-time access is terrible, because every byte costs a system call. Buffering fixes most of that for sequential reading. Memory mapping is a bit faster still, and it's far faster than RandomAccessFile when you need to jump around. The biggest win in the last line comes from processing the mapped buffer in bulk instead of a byte at a time. The lesson: avoid per-byte calls in any case, and consider mapping for large files with random access patterns.
Mapping a file
First, get a channel for the file. A FileChannel is a connection to a file that exposes operating system features: memory mapping, file locking (article 31), and fast transfers between channels.
FileChannel channel = FileChannel.open(path); // read only
FileChannel channel = FileChannel.open(path, READ, WRITE); // read and write
The options are the StandardOpenOptions from article 26. Older code gets a channel from a stream or random-access file with getChannel().
Then call map with a mode, a starting position and a size:
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
| Mode | Behavior |
|---|---|
READ_ONLY | the buffer can only be read; writes throw ReadOnlyBufferException |
READ_WRITE | changes are written back to the file eventually; other programs mapping the same file may not see them immediately (this depends on the operating system) |
PRIVATE | the buffer is writable, but changes stay private to it (copy-on-write) and never reach the file |
The channel must be opened compatibly. READ_WRITE and PRIVATE both need a channel opened for reading and writing, even though PRIVATE changes never reach the file; otherwise map throws NonWritableChannelException. A mapping stays valid even after the channel is closed.
Using a MappedByteBuffer
A MappedByteBuffer is a ByteBuffer, so you use the buffer methods (covered in detail in the next article). Buffers support sequential access, where get() reads at the current position and advances it:
while (buffer.hasRemaining()) {
byte b = buffer.get();
...
}
They also support random access with an index, leaving the position alone:
for (int i = 0; i < buffer.limit(); i++) {
byte b = buffer.get(i);
...
}
Bulk methods read and write arrays: get(byte[]), put(byte[]). Typed methods getInt, getLong, getShort, getChar, getFloat and getDouble read binary numbers, and the put counterparts write them, all with or without an index. Like the data streams, buffers default to big-endian order. For little-endian files, call buffer.order(ByteOrder.LITTLE_ENDIAN), and buffer.order() reports the current order.
Changes to a READ_WRITE mapping are written back at some point, at the latest when the mapping is released. To write them to the storage device now, for example before reporting success, call buffer.force().
Limits and pitfalls
- 2 GB per buffer. A
ByteBufferis indexed byint, so one mapping can cover at mostInteger.MAX_VALUEbytes. For bigger files, map several regions, or use aMemorySegment(below). - No unmap method. A
MappedByteBufferstays mapped until it's garbage collected. On Windows, that means you can't delete or truncate the file while an old mapping lingers. On any system, mapping many large files can exhaust address space or file handles. - Truncation by others. If another process shrinks a file while you have it mapped, accessing the missing part can crash with an internal error instead of a clean exception.
- Mapping has setup costs. For small files, or for a single sequential pass, plain buffered reading is just as fast and simpler.
MemorySegment mapping (Java 22)
The Foreign Function and Memory API (Part 13), final since Java 22, adds a better way to map files. FileChannel.map has an overload that takes an Arena and returns a MemorySegment:
try (FileChannel channel = FileChannel.open(path);
Arena arena = Arena.ofConfined()) {
MemorySegment segment = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size(), arena);
byte first = segment.get(ValueLayout.JAVA_BYTE, 0);
...
} // the mapping is released here, deterministically
This fixes the two big weaknesses of MappedByteBuffer. Segments are indexed by long, so a single mapping can exceed 2 GB. And the mapping is released when the arena closes, at a predictable point, instead of whenever the garbage collector gets around to it. Accessing a segment after its arena is closed throws an IllegalStateException, not a crash. Note that ValueLayout.JAVA_INT uses the platform's native byte order. Use .withOrder(ByteOrder.BIG_ENDIAN) to read data written by Java's data streams.
A complete example
The demo writes a 500 KB file with a deterministic pattern, computes its checksum five ways (all must agree), then tries each mapping mode and finally maps the file into a MemorySegment. Timings aren't printed because they vary between machines.
import java.io.*;
import java.lang.foreign.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.file.*;
import java.util.zip.*;
import static java.nio.file.StandardOpenOption.*;
public class Solution {
static long checksumInputStream(Path file) throws IOException {
try (InputStream in = Files.newInputStream(file)) {
var crc = new CRC32();
int c;
while ((c = in.read()) != -1) crc.update(c);
return crc.getValue();
}
}
static long checksumBufferedInputStream(Path file) throws IOException {
try (var in = new BufferedInputStream(Files.newInputStream(file))) {
var crc = new CRC32();
int c;
while ((c = in.read()) != -1) crc.update(c);
return crc.getValue();
}
}
static long checksumRandomAccessFile(Path file) throws IOException {
try (var raf = new RandomAccessFile(file.toFile(), "r")) {
var crc = new CRC32();
for (long p = 0, n = raf.length(); p < n; p++) crc.update(raf.readByte());
return crc.getValue();
}
}
static long checksumMappedFile(Path file) throws IOException {
try (FileChannel channel = FileChannel.open(file)) {
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
var crc = new CRC32();
for (int p = 0; p < buffer.limit(); p++) crc.update(buffer.get(p));
return crc.getValue();
}
}
static long checksumMappedBulk(Path file) throws IOException {
try (FileChannel channel = FileChannel.open(file)) {
var crc = new CRC32();
crc.update(channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size())); // whole buffer at once
return crc.getValue();
}
}
interface Checksum { long compute(Path p) throws IOException; }
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("mapped", ".bin");
byte[] data = new byte[500_000];
for (int i = 0; i < data.length; i++) data[i] = (byte) (i * 31 + i / 7);
Files.write(file, data);
String[] names = { "input stream", "buffered input stream", "random access file", "mapped, byte by byte", "mapped, bulk update" };
Checksum[] methods = { Solution::checksumInputStream, Solution::checksumBufferedInputStream,
Solution::checksumRandomAccessFile, Solution::checksumMappedFile, Solution::checksumMappedBulk };
for (int i = 0; i < methods.length; i++) {
System.out.printf("%-22s %08x%n", names[i], methods[i].compute(file));
}
// READ_WRITE: changes go back to the file
try (FileChannel channel = FileChannel.open(file, READ, WRITE)) {
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 16);
buffer.putInt(0, 0xCAFEBABE);
buffer.force(); // write the change to the storage device now
}
System.out.printf("after READ_WRITE mapping, first int in file: %08x%n",
ByteBuffer.wrap(Files.readAllBytes(file)).getInt());
// PRIVATE: copy-on-write, the file stays unchanged
try (FileChannel channel = FileChannel.open(file, READ, WRITE)) {
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.PRIVATE, 0, 16);
buffer.putInt(0, 0);
System.out.printf("PRIVATE buffer sees %08x, ", buffer.getInt(0));
}
System.out.printf("file still has %08x%n", ByteBuffer.wrap(Files.readAllBytes(file)).getInt());
// READ_ONLY buffers reject writes
try (FileChannel channel = FileChannel.open(file)) {
channel.map(FileChannel.MapMode.READ_ONLY, 0, 4).putInt(0, 1);
} catch (ReadOnlyBufferException e) {
System.out.println("writing to a READ_ONLY mapping: ReadOnlyBufferException");
}
// little-endian view of the same bytes
try (FileChannel channel = FileChannel.open(file)) {
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, 4);
System.out.printf("big-endian %08x, little-endian %08x%n",
buffer.getInt(0), buffer.order(ByteOrder.LITTLE_ENDIAN).getInt(0));
}
// Java 22: map into a MemorySegment, unmapped when the arena closes
try (FileChannel channel = FileChannel.open(file); Arena arena = Arena.ofConfined()) {
MemorySegment segment = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size(), arena);
long sum = 0;
for (long i = 0; i < segment.byteSize(); i++) sum += segment.get(ValueLayout.JAVA_BYTE, i) & 0xFF;
System.out.println("segment size " + segment.byteSize() + ", byte sum " + sum);
System.out.printf("first int (big-endian): %08x%n",
segment.get(ValueLayout.JAVA_INT_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN), 0));
}
Files.delete(file);
}
}
input stream f889ce07
buffered input stream f889ce07
random access file f889ce07
mapped, byte by byte f889ce07
mapped, bulk update f889ce07
after READ_WRITE mapping, first int in file: cafebabe
PRIVATE buffer sees 00000000, file still has cafebabe
writing to a READ_ONLY mapping: ReadOnlyBufferException
big-endian cafebabe, little-endian bebafeca
segment size 500000, byte sum 63714768
first int (big-endian): cafebabe
Common questions
Does mapping a file load the whole file into memory? No. The mapping only reserves address space. The operating system reads pages from disk when they are first accessed and can drop them again under memory pressure. That is why you can map files larger than the available RAM, as long as the address space is large enough, which it always is on 64-bit systems.
Do other processes see the changes I make through a mapping?
With READ_WRITE mode, usually: on mainstream operating systems the mapping is shared, so another process that maps the same file typically sees the changes, often before they reach the disk. The Java specification doesn't guarantee it, though. That makes mapped files a way to share memory between processes. Combine it with file locking (article 31) or atomic operations to coordinate. PRIVATE mappings are copy-on-write and never visible to others.
Can several threads use one MappedByteBuffer?
Not with relative get and put, because they share the buffer's position. Use absolute methods such as getInt(index), which do not change the position, or give each thread its own view with duplicate() or slice(). A MemorySegment from a shared arena has no position at all and is designed for concurrent access.
How do I unmap a MappedByteBuffer now?
There is no supported way. Old code used internal sun.misc or Unsafe cleaner methods, which are being phased out. The supported solution is to map through an Arena into a MemorySegment and close the arena.
When should I not use memory mapping? For small files, a single sequential pass, files on network drives (a dropped connection becomes a fault during memory access), and files that other programs may truncate. Buffered streams or channels are simpler and safer there.
API reference
java.nio.channels.FileChannel
| Method | Description |
|---|---|
static FileChannel open(Path path, OpenOption... options) | opens a channel; read-only by default |
long size() | the current file size |
MappedByteBuffer map(FileChannel.MapMode mode, long position, long size) | maps a region of at most 2 GB |
MemorySegment map(FileChannel.MapMode mode, long offset, long size, Arena arena) (Java 22) | maps a region into a segment whose lifetime is the arena's |
java.io.FileInputStream, FileOutputStream and RandomAccessFile
| Method | Description |
|---|---|
FileChannel getChannel() | the channel for the open file |
java.nio.MappedByteBuffer (a ByteBuffer)
| Method | Description |
|---|---|
MappedByteBuffer force() | writes changes to the storage device |
MappedByteBuffer load(), boolean isLoaded() | loads the content into physical memory, or checks whether it is |
java.nio.ByteBuffer (selected; see the next article)
| Method | Description |
|---|---|
byte get(), byte get(int index), ByteBuffer put(byte b), put(int index, byte b) | single bytes, sequential or indexed |
ByteBuffer get(byte[] dst), put(byte[] src) | bulk transfer |
int getInt(), getInt(int index), putInt(int value), putInt(int index, int value) (and Long, Short, Char, Float, Double) | binary numbers |
ByteBuffer order(ByteOrder bo), ByteOrder order() | set or get the byte order |
java.util.zip.CRC32
| Method | Description |
|---|---|
void update(int b), update(byte[] b), update(ByteBuffer buffer) | adds bytes to the checksum |
long getValue() | the CRC-32 value |
Summary
- Memory mapping makes a file region look like memory. For large files with random access it's much faster than
RandomAccessFile, and it avoids per-chunk system calls. - Get a
FileChannelwithFileChannel.open, thenmapwithREAD_ONLY,READ_WRITEorPRIVATE(copy-on-write). - A
MappedByteBufferis aByteBufferwith sequential and indexed access, typed getters and setters, a configurable byte order, andforce()to flush changes. - Buffer mappings are limited to 2 GB and can't be released explicitly.
- Java 22's
FileChannel.map(..., Arena)returns aMemorySegmentthat can be larger than 2 GB and is unmapped when the arena closes. - Process data in bulk where you can. Per-byte calls are slow whatever the API.
Practice Questions
Why is reading a file one byte at a time with FileInputStream.read() so slow, and what are two fixes?
Each read() is a separate call into the operating system. Wrap the stream in a BufferedInputStream, read into byte arrays, or map the file and access the buffer directly.
What's the difference between READ_WRITE and PRIVATE mappings?
With READ_WRITE, modifications are written back to the file. With PRIVATE, the buffer is writable, but modifications go to private copies of the pages and never reach the file.
How can you map a 6 GB file?
A single MappedByteBuffer is limited to 2 GB, so either map it in several regions, such as three 2 GB windows, or use Java 22's channel.map(mode, 0, channel.size(), arena), which returns a MemorySegment with long indexing.
On Windows, your program maps a file, finishes with it, then fails to delete it. Why?
A MappedByteBuffer stays mapped until it's garbage collected, and Windows refuses to delete a mapped file. Mapping into a MemorySegment with an arena, and closing the arena, releases the mapping deterministically.
A mapped file contains little-endian 32-bit integers. How do you read the third one?
buffer.order(ByteOrder.LITTLE_ENDIAN).getInt(8). Integers are 4 bytes, so the third one starts at byte offset 8, and the byte order must be set because buffers default to big-endian.
Previous: Java Directory Traversal: Files.list, walk, find, Glob Patterns and FileVisitor
Next: Java NIO Buffers: Capacity, Position, Limit, flip and compact
Related reading
- Java Directory Traversal: Files.list, walk, find, Glob Patterns and FileVisitor
- Java Files: Copying, Moving, Deleting and Reading File Attributes
- Java Files: Reading, Writing and Creating Files and Directories
- Java NIO Path: Creating, Resolving, Relativizing and Normalizing Paths
- Java ZIP Archives: ZipInputStream, ZipOutputStream and ZIP File Systems

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.