Software engineering · java · io · nio · networking · jvm · performance
Java I/O and NIO, Demystified
How Java I/O and NIO work, from reading a file and choosing a charset to decorators, Path and Files, buffers, channels, memory-mapped files, selectors, virtual threads and durable writes, explained from the basics up to what senior engineers need to know.
A straw and a bucket
There are two ways to move water out of a tank. You can drink it through a straw: you pull, water comes up, and you keep pulling until the tank is empty. Or you can use a bucket: you fill it, carry it over, pour it out, and come back with the empty bucket for more.
Java has both. The original java.io package (1996) is the straw. An InputStream hands you bytes as you ask for them, and your thread waits while it does. The java.nio package (2002, “new I/O”) is the bucket. You fill a ByteBuffer from a Channel, work on what is in it, empty it, and reuse it. NIO also added the part that made Java servers scale: a Selector, which lets one thread look after thousands of network connections, like one waiter keeping an eye on every table in a restaurant instead of one waiter standing at each table.
// java.io: pull bytes through a stream
try (InputStream in = new FileInputStream("photo.jpg")) {
byte[] chunk = new byte[8192];
int n;
while ((n = in.read(chunk)) != -1) {
process(chunk, n);
}
}
// java.nio: fill a buffer from a channel, then drain it
try (FileChannel ch = FileChannel.open(Path.of("photo.jpg"))) {
ByteBuffer buf = ByteBuffer.allocate(8192);
while (ch.read(buf) != -1) {
buf.flip(); // switch from filling to draining
process(buf);
buf.clear(); // empty the bucket for the next trip
}
}
NIO didn’t replace java.io. Most code uses both, and modern Java blurs the line: Files.newInputStream returns a classic InputStream that is backed by a channel, and the virtual threads of Java 21 make plain blocking I/O scale the way only NIO used to. This article starts with the everyday tasks, reading and writing files correctly, and goes down to what senior engineers need: buffers and their state machine, what a read costs in system calls and copies, zero-copy transfers, memory-mapped files, selectors, virtual threads and how to make a write survive a power cut. It continues the series after The Java Streams API; despite the name, InputStream has nothing to do with java.util.stream.
The basics: reading and writing a file
For most files, you don’t need streams, buffers or channels at all. The Files class (Java 7, with more methods in Java 11) does the whole job in one call:
Path path = Path.of("notes.txt");
String text = Files.readString(path); // whole file as one string (Java 11)
List<String> lines = Files.readAllLines(path); // whole file as lines
byte[] bytes = Files.readAllBytes(Path.of("logo.png")); // whole file as bytes
Files.writeString(path, "hello\n"); // create or replace (Java 11)
Files.writeString(path, "more\n", StandardOpenOption.APPEND); // add to the end
Files.write(Path.of("out.txt"), List.of("one", "two")); // one line per element
These methods read the whole file into memory. That is fine for a configuration file or a small JSON document, and wrong for a 4 GB log. For big files, read a piece at a time:
try (BufferedReader reader = Files.newBufferedReader(Path.of("access.log"))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(" 500 ")) {
System.out.println(line);
}
}
}
// or, the same as a stream of lines
try (Stream<String> lines = Files.lines(Path.of("access.log"))) {
long errors = lines.filter(l -> l.contains(" 500 ")).count();
}
Both hold only a small buffer in memory, however big the file is.
Always close what you open
An open file holds an operating system file descriptor, and a process gets a limited number of them (often 1,024 by default on Linux). The garbage collector doesn’t close files for you in any predictable way, so a service that forgets to close them eventually fails with Too many open files.
The fix is try-with-resources (Java 7). Anything that implements AutoCloseable and is declared in the parentheses is closed when the block ends, whether it ends normally or with an exception:
try (InputStream in = Files.newInputStream(src);
OutputStream out = Files.newOutputStream(dst)) {
in.transferTo(out); // copy everything (Java 9)
} // out is closed first, then in
Resources close in the reverse order they were opened. If both the body and close() throw, you get the body’s exception, with the one from close() attached as a suppressed exception, so nothing is lost. Before Java 7, getting this right took a nested try/finally for every resource, and most code got it wrong.
IOException is checked
Almost every I/O method declares throws IOException, so the compiler makes you handle it or declare it. Two subclasses are worth knowing by name: FileNotFoundException from the old API and NoSuchFileException from the new one. Inside lambdas, which can’t throw checked exceptions, wrap it in UncheckedIOException, as covered in Java Lambdas and Functional Interfaces.
Bytes and characters
java.io has two families, and choosing the wrong one is the source of most garbled text:
| Bytes | Characters | |
|---|---|---|
| Reading | InputStream |
Reader |
| Writing | OutputStream |
Writer |
| Unit | byte (8 bits) |
char (16 bits, UTF-16) |
| Use for | Images, archives, network protocols, anything binary | Text |
| From a file | FileInputStream, Files.newInputStream |
FileReader, Files.newBufferedReader |
| In memory | ByteArrayInputStream |
StringReader |
A file on disk only holds bytes. Text is bytes plus an agreement about what they mean, called a charset or encoding. The word “café” is five bytes in UTF-8 (é takes two) and four bytes in ISO-8859-1. Read UTF-8 bytes as ISO-8859-1 and you get “café”.
The bridge between the families is InputStreamReader and OutputStreamWriter. They take a byte stream and a charset, and decode or encode as data passes through:
// Text arriving over a socket as UTF-8 bytes
Reader reader = new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8);
Always say which charset you mean. Before Java 18, the classes that didn’t take a charset, such as FileReader, FileWriter, new String(bytes) and String.getBytes(), used the operating system’s default. That was UTF-8 on Linux and macOS but, on Windows, usually a legacy code page such as windows-1252, so the same program read the same file differently depending on where it ran. Java 18 (JEP 400) made UTF-8 the default everywhere. That fixed the common case, but naming the charset still documents your intent and protects code that runs on older JVMs. The Files methods (readString, newBufferedReader, lines) have always defaulted to UTF-8.
A related trap: a char is a UTF-16 code unit, not a character. Emoji and many rarer scripts need two chars, a surrogate pair, so "😀".length() is 2. Cutting a string or a buffer at an arbitrary char can split one.
Decorators: stacking streams
The classes in java.io are designed to be stacked. Each one wraps another stream and adds one feature, a pattern called the decorator. To read a gzipped UTF-8 log line by line, you stack four:
try (BufferedReader reader = new BufferedReader( // 4. lines, and a buffer
new InputStreamReader( // 3. bytes to characters
new GZIPInputStream( // 2. decompress
new FileInputStream("app.log.gz")), // 1. raw bytes from the file
StandardCharsets.UTF_8))) {
reader.lines().filter(l -> l.startsWith("ERROR")).forEach(System.out::println);
}
Closing the outermost one closes them all. Each layer knows nothing about the others: GZIPInputStream works the same over a file, a socket or a byte array.
The useful decorators:
| Class | Adds |
|---|---|
BufferedInputStream, BufferedOutputStream |
A buffer (8 KB by default) so small reads and writes don’t each go to the OS |
BufferedReader, BufferedWriter |
The same for characters, plus readLine() and newLine() |
DataInputStream, DataOutputStream |
Read and write int, long, double and so on in a fixed big-endian format |
GZIPInputStream, GZIPOutputStream, ZipInputStream |
Compression |
CipherInputStream, DigestInputStream |
Encryption and hashing on the fly |
PushbackInputStream |
Un-read a few bytes after peeking at them |
PrintStream, PrintWriter |
print, println and printf (and, beware, swallowing errors) |
Why buffering matters
Without a buffer, every read() of one byte on a FileInputStream is a call into the operating system. A system call is a switch from your program into the kernel and back, and costs from a few hundred nanoseconds to microseconds, which is a lot to pay for one byte.
// Slow: one system call per byte
try (InputStream in = new FileInputStream(file)) {
int b;
while ((b = in.read()) != -1) { count++; }
}
// Fast: one system call per 8 KB, then reads from memory
try (InputStream in = new BufferedInputStream(new FileInputStream(file))) {
int b;
while ((b = in.read()) != -1) { count++; }
}
On a 100 MB file, the first loop makes about 100 million system calls and the second about 13,000. On a 20 MB file on a Linux test machine, the unbuffered loop took about 6.5 seconds and the buffered one about 0.4 seconds, around 16 times faster. Reading into your own byte[] array of a few kilobytes has the same effect as the buffer, and skips the per-byte method calls as well. Writing is the same story, with a twist: a BufferedOutputStream holds your bytes until the buffer fills, until you call flush() or until you close it. Forget all three and the last few kilobytes never reach the file.
A read may return less than you asked for
InputStream.read(byte[] buf) returns how many bytes it read, and that can be anything from 1 to buf.length. Over a network it is routinely less: the data simply hasn’t all arrived yet. Code that assumes a full buffer works on local files in tests and corrupts data in production:
// Wrong: assumes read fills the array
byte[] header = new byte[16];
in.read(header);
// Right: keep reading until you have all 16 bytes, or fail at end of stream
byte[] header2 = in.readNBytes(16); // Java 11; may return fewer only at end of stream
new DataInputStream(in).readFully(header); // throws EOFException if the stream ends early
Paths and Files: the modern file API
java.io.File is the original way to name a file. It has problems that couldn’t be fixed without breaking code: many methods return false instead of saying what went wrong, it doesn’t understand symbolic links, and it is slow for large directories. Java 7 (NIO.2, JSR 203) replaced it with Path and the Files class.
| Task | java.io.File |
java.nio.file |
|---|---|---|
| Name a file | new File("a/b.txt") |
Path.of("a", "b.txt") (Java 11), Paths.get(...) |
| Delete | file.delete() returns false |
Files.delete(p) throws NoSuchFileException, DirectoryNotEmptyException… |
| Rename or move | file.renameTo(dest) returns false |
Files.move(p, dest, ATOMIC_MOVE) |
| Copy | Write it yourself | Files.copy(p, dest, REPLACE_EXISTING) |
| List a directory | file.listFiles(), one big array |
Files.list(p), Files.newDirectoryStream(p), lazy |
| Walk a tree | Write it yourself | Files.walk(p), Files.find(...), Files.walkFileTree(...) |
| Attributes | length(), lastModified() |
Files.size, Files.getLastModifiedTime, readAttributes, POSIX permissions |
| Symbolic links | Not supported | Files.isSymbolicLink, readSymbolicLink, LinkOption.NOFOLLOW_LINKS |
| Other file systems | No | Zip files, in-memory test file systems, through FileSystem |
Use Path for new code. When an old API wants a File, convert with path.toFile() and file.toPath().
A Path is only a name. Creating one doesn’t touch the disk, and its methods work on the text of the path:
Path base = Path.of("/srv/app");
Path conf = base.resolve("config/app.yaml"); // /srv/app/config/app.yaml
Path up = Path.of("/srv/app/logs/../config").normalize(); // /srv/app/config
Path rel = base.relativize(conf); // config/app.yaml
String name = conf.getFileName().toString(); // app.yaml
resolve and normalize are also how you defend against path traversal, where a user-supplied name like ../../etc/passwd escapes the folder you meant to serve:
Path root = Path.of("/srv/uploads").toAbsolutePath().normalize();
Path requested = root.resolve(userSuppliedName).normalize();
if (!requested.startsWith(root)) {
throw new SecurityException("outside the upload folder: " + userSuppliedName);
}
Path.startsWith compares whole name elements, so /srv/uploads-old doesn’t count as inside /srv/uploads, which a string startsWith would get wrong. If the folder can contain symbolic links, compare toRealPath() results instead, since normalize doesn’t follow links.
Walking directories
Files.walk and Files.list return lazy streams that hold a directory open, so they need try-with-resources just like Files.lines:
// Every .java file under src
try (Stream<Path> paths = Files.walk(Path.of("src"))) {
paths.filter(p -> p.toString().endsWith(".java"))
.forEach(System.out::println);
}
// Files.find filters using attributes the walk has already read
try (Stream<Path> big = Files.find(Path.of("/var/log"), 3,
(p, attrs) -> attrs.isRegularFile() && attrs.size() > 100_000_000)) {
big.forEach(System.out::println);
}
For a walk that needs to handle errors per file, skip subtrees or run code after a directory is finished (deleting a tree, for example), use Files.walkFileTree with a FileVisitor.
Open options
Files.newOutputStream, newBufferedWriter, write and FileChannel.open take StandardOpenOption values that say exactly what should happen:
| Option | Meaning |
|---|---|
CREATE |
Create the file if it doesn’t exist |
CREATE_NEW |
Create the file, and fail if it already exists (safe for lock files and unique names) |
TRUNCATE_EXISTING |
Empty an existing file first |
APPEND |
Write at the end |
WRITE, READ |
Open for writing, reading |
SYNC, DSYNC |
Every write goes all the way to the storage device before returning (slow; see durability below) |
DELETE_ON_CLOSE |
Delete when closed, for scratch files |
With no options, the write methods use CREATE, TRUNCATE_EXISTING and WRITE, which replaces the file.
Watching for changes
WatchService tells you when files in a directory are created, changed or deleted, which is handy for reloading configuration:
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Path.of("/etc/myapp");
dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
WatchKey key = watcher.take(); // blocks until something happens
for (WatchEvent<?> event : key.pollEvents()) {
Path changed = dir.resolve((Path) event.context());
reload(changed);
}
key.reset(); // forget this and you get no more events
}
It watches one directory, not a tree, and the events are hints, not guarantees: one save in an editor can produce several events, and on some platforms the JDK implementation polls, so an event can arrive seconds late.
Other things in java.io you will meet
RandomAccessFilereads and writes at any position in a file, withseek(position).FileChanneldoes the same job better, and you can get one from it withgetChannel().Scannerparses tokens and numbers from text. It is convenient for exercises and slow for big inputs, because it uses regular expressions for every token. For bulk parsing, read lines with aBufferedReaderand split them yourself.PrintWriterandPrintStreamnever throwIOException. They set an internal flag instead, which you can check withcheckError().System.outis aPrintStream, which is why printing to a closed pipe fails silently. Don’t use them for data where losing it matters.Consolereads passwords without echoing them, withSystem.console().readPassword(). Check fornull: there may be no console at all, for example in a container or a background service.ObjectInputStreamandObjectOutputStreamimplement Java serialization. Avoid them for anything new, and never useObjectInputStreamon data from a source you don’t trust. Reading a crafted byte stream can run code from classes on your class path, and this was behind many remote code execution bugs in the 2010s. If you are stuck with it, set a deserialization filter (JEP 290, Java 9, extended by JEP 415 in Java 17) that allows only the classes you expect. Use JSON, Protocol Buffers or another explicit format instead.
The mistakes everyone makes
- Not closing. Use try-with-resources for every stream, reader, channel and
Files.lines,Files.listorFiles.walkstream. - Reading or writing one byte at a time without a buffer. Wrap in
BufferedInputStreamorBufferedOutputStream, or work in arrays of a few kilobytes. - Assuming
readfills the array. It returns a count. UsereadNBytesorreadFully. - Forgetting to flush. A buffered writer that is never flushed or closed loses its tail.
- Leaving the charset to chance.
new String(bytes),getBytes(),FileReaderandFileWriterwithout a charset meant “whatever this machine uses” before Java 18. Files.readAllByteson a file of unknown size. It loads the whole thing, and a large one throwsOutOfMemoryError. Files over 2 GB can’t fit in an array at all.File.delete()andrenameTo()without checking the result. They fail quietly. UseFiles.deleteandFiles.move, which throw an exception that says why.- Building paths with string concatenation.
dir + "/" + namebreaks on Windows and invites path traversal. Useresolve. - Swallowing
PrintWritererrors. It never throws. CheckcheckError(), or use aBufferedWriter. - Calling
flush()and believing the data is safe.flushmoves bytes from Java into the operating system, not onto the disk. See durability below.
Advanced ideas
Everything above is enough to do file and stream I/O well. The rest of this article explains what happens underneath, which is what you need when you are tuning throughput, writing a server or a storage engine, or debugging why the data didn’t survive a crash.
What a read actually costs
When you call read on a FileInputStream, a lot happens below Java:
- The JVM makes a
readsystem call, switching the CPU from user mode into the kernel. - The kernel looks in its page cache, the memory it keeps for recently used file data. If the data is not there, it asks the disk for it, and your thread waits.
- The kernel copies the bytes from the page cache into the memory the JVM gave it.
- For a
byte[]on the Java heap, the JVM may copy them once more, because the garbage collector can move heap objects around, and the kernel needs an address that holds still while it writes.
Writing a file and then sending it over a socket with plain streams repeats all of that in both directions: kernel to user space on the read, user space back to kernel on the write. The data crosses the boundary twice and does nothing useful in your process except pass through. That double copy is what NIO’s buffers and channels are designed to avoid.
Buffers: the bucket and its three markers
A ByteBuffer is a fixed-size block of bytes with three numbers that track where you are:
- capacity: the size of the buffer. It never changes.
- position: where the next byte will be read or written.
- limit: the first position you are not allowed to touch.
A new buffer is ready for filling: position 0, limit equal to capacity. Every put, or a channel’s read into the buffer, advances the position. To start draining it, you call flip(), which sets the limit to the current position (the end of the data you wrote) and the position back to 0. Every get, or a channel’s write from the buffer, advances the position again, up to the limit.
ByteBuffer buf = ByteBuffer.allocate(8); // position=0 limit=8 capacity=8
buf.put((byte) 'h').put((byte) 'e').put((byte) 'l').put((byte) 'l').put((byte) 'o');
// position=5 limit=8
buf.flip(); // position=0 limit=5: ready to drain
byte a = buf.get(), b = buf.get(), c = buf.get();
// position=3 limit=5: "lo" still unread
buf.compact(); // moves "lo" to the front
// position=2 limit=8: ready to fill again
The methods that move the markers are the whole API, and mixing them up is the classic NIO bug:
| Method | Position | Limit | Use it |
|---|---|---|---|
flip() |
0 | old position | After filling, before draining |
clear() |
0 | capacity | After draining everything, before filling again (it doesn’t erase the bytes) |
compact() |
after the unread bytes | capacity | After draining part of it, to keep the rest |
rewind() |
0 | unchanged | Drain the same data again |
mark(), reset() |
saved and restored | unchanged | Go back to a remembered position |
remaining() |
limit - position, how much is left |
Forgetting flip() before writing sends nothing, or the garbage after your data. Calling clear() when part of the data is unread silently drops it. With a network protocol, where messages don’t line up with reads, compact() is usually the right call.
Buffers also give you typed access and control over byte order, which DataInputStream doesn’t:
ByteBuffer header = ByteBuffer.allocate(12).order(ByteOrder.LITTLE_ENDIAN);
header.putInt(magic).putLong(timestamp).flip();
int version = buf.getInt(4); // absolute get: reads at index 4, position doesn't move
ByteBuffer body = buf.slice(16, 64); // a view of bytes 16 to 79, sharing the same memory (Java 13)
Byte buffers are big-endian by default, whatever the CPU, so they match network byte order. The other buffer types (CharBuffer, IntBuffer, LongBuffer and so on) work the same way. A buffer is not thread-safe: its markers are plain fields.
Heap buffers and direct buffers
There are two kinds of ByteBuffer:
ByteBuffer heap = ByteBuffer.allocate(64 * 1024); // a byte[] on the Java heap
ByteBuffer direct = ByteBuffer.allocateDirect(64 * 1024); // native memory outside the heap
A heap buffer is a wrapper around a byte[]. It is cheap to create and the garbage collector manages it, but the kernel can’t safely write into memory the collector might move. When you pass one to a channel, the JDK copies the data through a temporary direct buffer it keeps for each thread.
A direct buffer lives in native memory at a fixed address, so the kernel reads and writes it directly with no extra copy. In exchange:
- It is slow to allocate and free, so allocate a few and reuse them. Don’t create one per request.
- Its memory doesn’t count towards
-Xmx. It is capped separately by-XX:MaxDirectMemorySize, which defaults to roughly the maximum heap size. Hit it and you getOutOfMemoryError: Direct buffer memory. - It is freed only when the small
ByteBufferobject on the heap is garbage collected. A heap with plenty of room may not collect for a long time while native memory fills up.
There is also a subtle leak: the per-thread temporary buffers the JDK uses for heap buffers grow to the largest buffer that thread ever wrote. A pool of 200 threads that each once wrote a 50 MB heap buffer holds 10 GB of native memory. The system property jdk.nio.maxCachedBufferSize caps the size the JDK will cache.
The rule of thumb: use direct buffers for long-lived, reused I/O buffers in servers and storage code, and heap buffers for everything else. Netty and other networking libraries keep pools of direct buffers for exactly this reason.
Channels
A channel is an open connection to something that can do I/O: a file, a socket, a pipe. Unlike a stream, a channel can usually both read and write, works with buffers instead of arrays, and for sockets can be put in non-blocking mode.
FileChannel adds things streams can’t do:
try (FileChannel ch = FileChannel.open(path, READ, WRITE)) {
long size = ch.size();
// Positional reads and writes: no shared file pointer, safe from many threads
ByteBuffer page = ByteBuffer.allocateDirect(4096);
ch.read(page, 3 * 4096L); // read page 3, doesn't move the channel's position
// Gather write: several buffers in one system call (writev)
ByteBuffer header = encodeHeader(record), body = encodeBody(record);
ch.write(new ByteBuffer[] { header, body });
ch.truncate(size / 2); // cut the file
ch.force(true); // flush to the device (see durability)
}
Positional read(buf, position) and write(buf, position) are what databases use: many threads read different pages of one file at once, with no locking around a shared position. Scatter reads and gather writes (read(ByteBuffer[]), write(ByteBuffer[])) fill or drain several buffers in one system call, which suits formats with a fixed header and a variable body.
Like read, a channel’s write may write only part of the buffer, particularly on sockets. Always loop:
while (buf.hasRemaining()) {
channel.write(buf);
}
Zero-copy transfers
FileChannel.transferTo and transferFrom ask the operating system to move bytes between two channels without bringing them into the JVM at all:
try (FileChannel file = FileChannel.open(Path.of("video.mp4"));
SocketChannel socket = SocketChannel.open(new InetSocketAddress(host, 8080))) {
long position = 0, size = file.size();
while (position < size) {
position += file.transferTo(position, size - position, socket);
}
}
On Linux, a file-to-socket transfer becomes the sendfile system call: the kernel sends data straight from the page cache to the network stack. Recent JDKs can also use copy_file_range for file-to-file copies on Linux, which some file systems turn into a near-instant copy-on-write clone. This is how Kafka serves stored messages to consumers so cheaply, and how web servers send static files. Note the loop: transferTo can move fewer bytes than asked, and a single call is limited to 2 GB on some platforms.
InputStream.transferTo(OutputStream) (Java 9) sounds similar but is an ordinary read-and-write loop through a buffer in Java. Newer JDKs special-case some pairs, such as two file streams, to use channel transfers underneath, but don’t count on zero copy unless you use FileChannel yourself. Files.copy(Path, Path) already uses the platform’s fast copy paths where it can.
Memory-mapped files
FileChannel.map asks the operating system to make a file appear as memory. You get a MappedByteBuffer, and reading from it reads the file:
try (FileChannel ch = FileChannel.open(Path.of("index.bin"), READ)) {
MappedByteBuffer map = ch.map(FileChannel.MapMode.READ_ONLY, 0, ch.size());
long entry = map.getLong(1_024 * 8); // no read call: just memory access
}
No data is copied when you map. The first time you touch a page, the CPU raises a page fault, the kernel loads that 4 KB page from disk into the page cache and maps it into your process, and the access continues. After that, reads are plain memory reads with no system calls. The operating system decides what stays in memory and pages out what isn’t used, so a 50 GB file can be mapped on a machine with 8 GB of RAM. Lucene’s index files and many embedded databases work this way.
The catches:
- The 2 GB limit. A
MappedByteBufferis indexed byint, so one mapping is at most 2 GB. Large files need many mappings. - No way to unmap. The mapping lives until the buffer is garbage collected. Until then the file can’t be deleted on Windows, and on any platform the address space stays in use.
- Page faults block. A first touch on a page that isn’t in the cache waits for the disk, inside what looks like a plain memory read. It doesn’t show up as I/O in a profiler, and it can’t be interrupted. Pages count as the process’s memory in some monitoring tools, which can confuse container memory limits.
- Truncation crashes. If another process shrinks the file while it is mapped, touching the missing part can kill the JVM with
SIGBUSor cause anInternalError, depending on the platform and JDK. - Writes need
force(). WithMapMode.READ_WRITE, changes reach the page cache at once, but reach the disk only when the OS decides to, or when you callmap.force().
Java 22 finalised the Foreign Function & Memory API (JEP 454), which fixes the first two problems. FileChannel.map gained an overload that returns a MemorySegment, indexed by long, and tied to an Arena you can close to unmap it at a moment you choose:
try (Arena arena = Arena.ofConfined();
FileChannel ch = FileChannel.open(Path.of("big.bin"), READ)) {
MemorySegment seg = ch.map(FileChannel.MapMode.READ_ONLY, 0, ch.size(), arena);
long value = seg.get(ValueLayout.JAVA_LONG, 10_000_000_000L); // past 2 GB
} // arena closed: the file is unmapped here
Memory mapping isn’t automatically faster than reading. For a single sequential pass, read into a reused buffer is usually as fast or faster, because the kernel’s read-ahead works well and there are no page faults. Mapping pays off for random access to data that is read many times, where it saves system calls and copies.
File locks
FileChannel.lock() and tryLock() take an operating system lock on a file or a region of it:
try (FileChannel ch = FileChannel.open(Path.of("app.lock"), CREATE, WRITE);
FileLock lock = ch.tryLock()) {
if (lock == null) {
throw new IllegalStateException("another instance is already running");
}
runApplication();
}
These locks are for coordinating between processes. They are held by the whole JVM, so two threads in the same JVM that lock overlapping regions get an OverlappingFileLockException rather than waiting for each other. On many systems they are advisory: a process that doesn’t ask for the lock can still read and write the file. Behaviour on network file systems such as NFS varies widely.
Blocking servers and the thread-per-connection model
The classic way to write a server with java.io gives every connection its own thread:
try (ServerSocket server = new ServerSocket(8080)) {
while (true) {
Socket client = server.accept(); // waits for a connection
pool.submit(() -> handle(client)); // one thread per connection
}
}
handle reads a request, which blocks until the bytes arrive, and writes a response. It is simple, and each connection’s code reads top to bottom. The problem is the threads. A platform thread is an operating system thread with a stack of about 1 MB reserved by default, and switching between thousands of them costs real CPU. A chat server with 50,000 mostly idle connections would need 50,000 threads that spend nearly all their time asleep, waiting for a message.
Selectors: one thread, many connections
NIO’s answer is non-blocking I/O with a selector. You put each socket channel in non-blocking mode, so read returns immediately with whatever is available, possibly nothing. You register the channels with a Selector and say which events you care about. Then one thread asks the selector, “which of these are ready?”, and handles only those:
Selector selector = Selector.open();
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress(8080));
server.configureBlocking(false);
server.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select(); // sleep until at least one channel is ready
Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
while (keys.hasNext()) {
SelectionKey key = keys.next();
keys.remove(); // the selector never removes keys for you
if (key.isAcceptable()) {
SocketChannel client = server.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(4096));
} else if (key.isReadable()) {
SocketChannel client = (SocketChannel) key.channel();
ByteBuffer buf = (ByteBuffer) key.attachment(); // each connection keeps its own buffer
int n = client.read(buf);
if (n == -1) { // the client closed the connection
key.cancel();
client.close();
continue;
}
buf.flip();
client.write(buf); // echo back what arrived
buf.compact(); // keep anything not yet written
}
}
}
On Linux, the selector is built on epoll, and on macOS and BSD on kqueue. Windows has its own implementation. These system calls let the kernel track thousands of sockets and wake the thread only for the ones that changed, so the cost doesn’t grow with the number of idle connections.
The price is in the code. With blocking I/O, the state of a conversation lives in local variables and the call stack: “I’ve read the header, now I’m reading the body”. With a selector, that state has to be stored by hand, in the key’s attachment, between events. Messages arrive in arbitrary pieces, so you have to collect partial data until a whole message is there. And the loop must never block, because one slow task stalls every connection on that thread. In practice, almost nobody writes raw selector code. Frameworks like Netty (underneath gRPC, Cassandra, Elasticsearch and many others), Vert.x and the HTTP servers in Undertow and Jetty wrap it in event loops, pipelines of handlers and pooled buffers.
Writes and back-pressure
The echo server above has a bug that every first NIO server has. If the client reads slowly, the kernel’s send buffer for that socket fills, and write writes only part of the data, or nothing. The code then compacts and keeps the rest, but nothing ever comes back to finish the write unless more data arrives.
The fix is to register interest in OP_WRITE while there is unwritten data, and remove it once the buffer is empty:
client.write(buf);
if (buf.hasRemaining()) {
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); // tell me when I can write more
} else {
key.interestOps(SelectionKey.OP_READ);
}
Don’t leave OP_WRITE registered all the time: a socket with room in its send buffer is almost always writable, so the selector would wake constantly with nothing to do. The deeper point is back-pressure: when the other side can’t keep up, a server must stop reading from the producer, rather than queue data in memory until it runs out. Blocking I/O gives you that for free, because a blocked write stops the thread. Non-blocking I/O makes you build it.
Asynchronous channels
Java 7 also added asynchronous channels, such as AsynchronousSocketChannel and AsynchronousFileChannel. Instead of asking which channels are ready, you start an operation and get called back, or get a Future, when it completes:
AsynchronousFileChannel ch = AsynchronousFileChannel.open(path, READ);
ByteBuffer buf = ByteBuffer.allocate(4096);
ch.read(buf, 0, buf, new CompletionHandler<Integer, ByteBuffer>() {
public void completed(Integer n, ByteBuffer b) { /* use the data */ }
public void failed(Throwable e, ByteBuffer b) { /* handle the error */ }
});
This is the completion model that Windows’ I/O completion ports use natively. On Linux, the JDK implements asynchronous sockets with epoll and a thread pool, and asynchronous file channels with a thread pool that does blocking reads, so there is no real gain over doing that yourself. They are rarely used directly. (Linux’s newer io_uring interface is a true completion API, but the JDK doesn’t use it yet.)
Virtual threads: blocking code that scales
Java 21 (JEP 444) added virtual threads, and they change the trade-off between the two server styles. A virtual thread is a Java thread managed by the JVM, not by the operating system. It is cheap enough to create millions. When one blocks on a socket read, the JVM takes it off its carrier (the platform thread actually running it), registers the socket with an internal poller built on the same epoll or kqueue a selector uses, and runs another virtual thread on that carrier. When data arrives, the virtual thread is scheduled again and its read returns.
So this plain, blocking, thread-per-connection server now handles tens of thousands of idle connections:
try (ServerSocket server = new ServerSocket(8080);
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
while (true) {
Socket client = server.accept();
executor.submit(() -> handle(client)); // a new virtual thread per connection
}
}
The code reads top to bottom, exceptions have useful stack traces, and back-pressure comes from blocking, as before. Underneath, the JVM is running a selector loop for you. For new request-response services, this is now usually the better choice than writing an event loop.
The limits are worth knowing:
- File I/O still blocks the carrier. Operating systems don’t offer non-blocking reads for regular files the way they do for sockets. The JDK makes up for it by temporarily adding a carrier thread while a virtual thread is stuck in a file operation. That works, but it means a burst of slow disk reads creates platform threads.
- Pinning. In Java 21 to 23, a virtual thread that blocks while inside a
synchronizedblock can’t be taken off its carrier, and enough of them can stall the whole scheduler. Java 24 (JEP 491) fixed this forsynchronized. Blocking inside native code still pins. - They don’t add capacity. A virtual thread makes waiting cheap, not work. A database with 50 connections still serves 50 queries at a time, and 10,000 virtual threads waiting for it are 10,000 queued requests. Use a semaphore or a bounded pool for scarce resources.
- Event loops still win at the extremes. Proxies and brokers that move bytes between hundreds of thousands of connections with minimal per-connection state, and need tight control over buffers and memory, still use Netty-style designs.
The Java 13 and 15 re-implementations of Socket, ServerSocket and DatagramSocket on top of NIO’s internals (JEPs 353 and 373) are what made this possible: the old java.net socket classes now share the NIO implementation, so they can park a virtual thread instead of blocking an OS thread.
Durability: when is it on the disk?
write returning doesn’t mean the data is on the disk. There are several layers between your program and the platters or flash cells, and each one can hold on to your bytes:
| Layer | Holds data until | Survives a JVM crash? | Survives a power cut? |
|---|---|---|---|
A Java buffer (BufferedOutputStream) |
flush() or close() |
No | No |
| The kernel’s page cache | The OS writes it back, usually within seconds | Yes | No |
| The drive’s own write cache | The drive decides, or a flush command | Yes | Only with a battery- or capacitor-backed cache |
| The storage medium | Yes | Yes |
flush() moves data from Java into the kernel. To get it onto the device, you need FileChannel.force(true) (or FileDescriptor.sync()), which makes an fsync system call. force(false) corresponds to fdatasync and skips metadata such as the modification time, which can save a disk write. StandardOpenOption.SYNC and DSYNC do the equivalent after every write, which is simpler and much slower.
Even fsync on the file isn’t the whole story when you create or rename files. The directory entry that names the file is separate metadata. The standard way to replace a file safely, so a crash leaves either the complete old version or the complete new one and never half of each, is write, sync, rename, sync the directory:
static void writeAtomically(Path target, byte[] data) throws IOException {
Path tmp = target.resolveSibling(target.getFileName() + ".tmp");
try (FileChannel ch = FileChannel.open(tmp, CREATE, TRUNCATE_EXISTING, WRITE)) {
ByteBuffer buf = ByteBuffer.wrap(data);
while (buf.hasRemaining()) {
ch.write(buf);
}
ch.force(true); // 1. the new contents are on the disk
}
Files.move(tmp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
// 2. one atomic rename
try (FileChannel dir = FileChannel.open(target.getParent(), READ)) {
dir.force(true); // 3. the rename itself is on the disk
} catch (IOException e) {
// opening a directory isn't supported on every platform (Windows); best effort
}
}
ATOMIC_MOVE maps to rename, which POSIX file systems guarantee is atomic within one file system. Opening a directory as a channel and forcing it works on Linux and macOS and is how you sync a directory from Java. Databases and message brokers build their write-ahead logs on exactly these calls, and they batch many writes into one force (a group commit), because each fsync can take milliseconds on a disk and hundreds of microseconds even on a fast SSD.
Memory-mapped writes need MappedByteBuffer.force() in the same way. Whatever the API, if nobody calls a force, a power cut can lose the last few seconds of writes the program believed were done.
Choosing an API
| You want to… | Use |
|---|---|
| Read or write a small file | Files.readString, readAllBytes, writeString, write |
| Process a large text file line by line | Files.newBufferedReader or Files.lines, in try-with-resources |
| Process a large binary file sequentially | Files.newInputStream with a reused byte[], or FileChannel with a reused buffer |
| Copy or move files | Files.copy, Files.move |
| Random access to a large file, read many times | FileChannel positional reads, or memory mapping |
| Send a file over a socket | FileChannel.transferTo |
| Write data that must survive a crash | FileChannel.force, write-then-rename |
| Write a network service | Blocking sockets on virtual threads, or a framework such as Netty |
| Handle a huge number of connections with tight memory control | Netty or a selector loop |
| Talk HTTP | java.net.http.HttpClient (Java 11), not raw sockets |
How Java compares
| Language | Equivalent | Notable difference |
|---|---|---|
| Go | io.Reader, io.Writer, goroutines |
Goroutines did for Go from the start what virtual threads do for Java: blocking code on top of epoll |
| C# | Stream, async/await, Span<T> |
Asynchronous I/O is part of the language; Stream serves both bytes and the async model |
| Rust | std::io::Read, Tokio |
Blocking I/O in the standard library; async I/O through libraries, built on epoll or io_uring |
| Node.js | Streams, the event loop (libuv) | Single-threaded event loop for everything; file I/O runs on a hidden thread pool, much like Java’s async file channels |
| Python | File objects, asyncio |
asyncio is an event loop in the style of a selector, with coroutines to hide the callbacks |
Key takeaways
- For everyday files, use
PathandFiles:readString,writeStringandlinescover most needs. Usejava.io.Fileonly where an old API demands it. - Know which family you are in:
InputStream/OutputStreamfor bytes,Reader/Writerfor text, and always name the charset at the boundary. - Close everything with try-with-resources, including streams from
Files.lines,listandwalk. - Buffer small reads and writes, don’t assume
readfills your array, and loop on channel writes andtransferTo. - NIO’s
ByteBufferhas a position, a limit and a capacity: fill it,flip(), drain it, thenclear()orcompact(). Use direct buffers for reused I/O buffers, and watch native memory. FileChannelgives you positional reads, gather writes, zero-copytransferTo, memory mapping and locks. Memory mapping wins for repeated random access, not for one sequential pass.- A selector lets one thread serve thousands of connections at the cost of hand-managed state and back-pressure. Virtual threads (Java 21) give the same scaling to plain blocking code, and are now the default choice for request-response servers.
flush()reaches the operating system, not the disk. Durable writes needforce()and, for replacing files, write, sync, rename, sync the directory.
Further reading
- The
java.niopackage documentation, and the class documentation ofBuffer,FileChannelandSelector, which define the exact rules for markers, partial transfers and selection - JSR 51 (NIO, Java 1.4) and JSR 203 (NIO.2, Java 7), the specifications that introduced buffers and channels, then
PathandFiles - JEP 400, “UTF-8 by Default”; JEP 353 and JEP 373, the socket re-implementations; JEP 444, “Virtual Threads”; JEP 454, “Foreign Function & Memory API”; JEP 491, “Synchronize Virtual Threads without Pinning”
- Ron Hitchens, Java NIO (O’Reilly), still the most complete explanation of buffers, channels and selectors
- Norman Maurer and Marvin Allen Wolfthal, Netty in Action (Manning), on how production systems wrap selectors
- The Linux man pages for
sendfile(2),mmap(2),fsync(2)andepoll(7), which describe what the JDK is asking the kernel to do - The
sun.nio.chpackage in the OpenJDK source, whereEPollSelectorImpl,FileChannelImplandUtil.getTemporaryDirectBuffershow the native calls and the buffer cache directly