unkletayo
24

Java NIO: channels, buffers, and serialization

What NIO channels and ByteBuffer add over streams, how non-blocking I/O works, and why Java serialization is worth avoiding.

Adetayo Akinsanya2026-11-108 min read

  • Java
  • Core Java
  • I/O
  • NIO
  • Channels
  • Serialization

Part 24 of the series.Read How Java navigates the filesystem: files, paths, and I/O (Part 23) first if you have not.

In this article (8 sections)
  1. What a channel is
  2. ByteBuffer: a positioned memory region
  3. Reading a file with FileChannel
  4. Random access
  5. Memory-mapped files
  6. Non-blocking I/O and Selector
  7. Java object serialization
  8. Resource lifetime
try (FileChannel channel = FileChannel.open(Path.of("data.bin"), StandardOpenOption.READ)) {
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    while (channel.read(buffer) != -1) {
        buffer.flip();
        process(buffer);
        buffer.clear();
    }
}

This reads a file in 4096-byte chunks without loading the whole file into memory. The channel is not a stream: it’s bidirectional, it works with buffers rather than individual bytes, and it can operate without blocking a thread. This part explains what that means and when it matters.

What a channel is

A Channel represents a connection to an I/O resource: a file, a socket, a pipe. Where a stream is directional (an InputStream reads, an OutputStream writes), a channel is typically bidirectional. FileChannel can read and write the same file. SocketChannel can read and write on the same connection.

Channels don’t work with individual bytes. They work with Buffer objects — fixed-size memory regions that hold data to be read or written.

The core operations on a ReadableByteChannel:

int bytesRead = channel.read(buffer);  // fills buffer from the channel

And on WritableByteChannel:

int bytesWritten = channel.write(buffer);  // drains buffer to the channel

Both return the number of bytes transferred, or -1 at end of stream.

ByteBuffer: a positioned memory region

ByteBuffer is the workhorse of NIO. It wraps a byte array with three tracked positions:

  • capacity: the total size of the underlying array — fixed at creation.
  • limit: the boundary beyond which data should not be read or written — the “active” region.
  • position: the current read/write cursor.

When you create a buffer and write into it, position advances. When you switch from writing to reading, you call flip(). Flip sets limit = position and position = 0, so reading starts at the beginning and stops where writing stopped. When you’re done reading and want to reuse the buffer, call clear(): it resets position = 0 and limit = capacity.

ByteBuffer buffer = ByteBuffer.allocate(8);
// capacity=8, limit=8, position=0

buffer.put((byte) 65);  // writes 'A'
buffer.put((byte) 66);  // writes 'B'
// position=2

buffer.flip();
// limit=2, position=0

buffer.get();  // returns 65 ('A'), position=1
buffer.get();  // returns 66 ('B'), position=2

buffer.clear();
// limit=8, position=0 — ready to write again

The flip/clear pattern is the main source of bugs with ByteBuffer. Forgetting flip() before reading means you read from position onward (which is the end of the written data), and you get garbage or nothing.

Reading a file with FileChannel

FileChannel.open opens a file channel with the specified options. Reading is the same read-flip-clear loop from the opening example:

try (FileChannel channel = FileChannel.open(
        Path.of("data.bin"), StandardOpenOption.READ)) {
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    while (channel.read(buffer) != -1) {
        buffer.flip();
        while (buffer.hasRemaining()) {
            byte b = buffer.get();
            process(b);
        }
        buffer.clear();
    }
}

buffer.hasRemaining() returns position < limit, so the inner loop drains the buffer completely before the outer loop fills it again.

For most file reading, Files.readAllBytes or Files.newBufferedReader from the previous part are simpler. FileChannel earns its verbosity when you need random access, memory mapping, or file locking.

Random access

FileChannel has a position(long) method that seeks to a byte offset within the file — something streams cannot do:

try (FileChannel channel = FileChannel.open(
        Path.of("index.bin"), StandardOpenOption.READ)) {
    channel.position(1024);  // seek to byte 1024
    ByteBuffer buffer = ByteBuffer.allocate(16);
    channel.read(buffer);
    buffer.flip();
    // read the 16 bytes starting at offset 1024
}

channel.size() returns the current file size in bytes.

Memory-mapped files

For very large files that need frequent random reads, FileChannel.map maps a region of the file directly into the process’s virtual address space:

try (FileChannel channel = FileChannel.open(
        Path.of("large.bin"), StandardOpenOption.READ)) {
    MappedByteBuffer mapped = channel.map(
        FileChannel.MapMode.READ_ONLY, 0, channel.size());
    // mapped behaves like a ByteBuffer backed by the file
    byte first = mapped.get(0);
    byte last  = mapped.get((int) channel.size() - 1);
}

The OS handles paging: only the pages actually accessed are loaded from disk. For read-mostly workloads on large data files (logs, databases, indices), this can be faster than read loops because it avoids copying data through a kernel buffer into a Java byte array.

The MappedByteBuffer survives the channel being closed. The underlying mapping lives until the buffer is garbage collected, though the JVM does not guarantee when that happens.

Non-blocking I/O and Selector

For network servers, the blocking model — one thread per connection, each thread blocking on reads and writes — becomes expensive when connection counts reach thousands. NIO addresses this with non-blocking channels and Selector.

A SocketChannel can be switched to non-blocking mode:

SocketChannel client = SocketChannel.open();
client.configureBlocking(false);

In non-blocking mode, channel.read(buffer) returns immediately: it transfers whatever bytes are available right now, which may be zero. The caller must check and retry rather than wait.

Selector multiplexes many non-blocking channels onto one thread. You register channels with the selector and specify which events you care about (OP_READ, OP_WRITE, OP_ACCEPT, OP_CONNECT). Then selector.select() blocks until at least one channel is ready:

Selector selector = Selector.open();
channel.register(selector, SelectionKey.OP_READ);

while (true) {
    selector.select();  // blocks until something is readable
    Set<SelectionKey> ready = selector.selectedKeys();
    for (SelectionKey key : ready) {
        if (key.isReadable()) {
            SocketChannel ch = (SocketChannel) key.channel();
            ch.read(buffer);
            // handle data
        }
    }
    ready.clear();
}

This is the reactor pattern: one thread drives many connections. For most Java server applications you won’t write this directly — Netty, Vert.x, and Java’s own java.net.http.HttpClient handle NIO internally. But knowing the model explains why those frameworks can serve ten thousand concurrent connections with a handful of threads.

Java object serialization

Serializable is a marker interface. A class that implements it is telling the JVM: “you may convert instances of this class to a byte stream and reconstruct them later.” This is Java’s built-in object serialization.

class Account implements Serializable {
    String owner;
    double balance;
}

// writing:
try (ObjectOutputStream out = new ObjectOutputStream(
        new FileOutputStream("account.ser"))) {
    out.writeObject(new Account("Adetayo", 5000));
}

// reading:
try (ObjectInputStream in = new ObjectInputStream(
        new FileInputStream("account.ser"))) {
    Account account = (Account) in.readObject();
}

The mechanism works. The problems are severe enough that it appears on most “do not use in new code” lists today.

What can go wrong. readObject() throws ClassNotFoundException if the class structure has changed in a way the serialization stream doesn’t match. It can also execute arbitrary code: gadget chains in the deserialized object graph can trigger actions during reconstruction. The JVM itself loaded classes and ran constructors for every object in the stream, based entirely on data you just read from an untrusted source. This is why Java deserialization vulnerabilities appear repeatedly in security advisories.

The serialization stream also creates a tight coupling between the class and its serialized form. Add a field, rename a field, change a type — the existing saved data may no longer load.

Use serialVersionUID if you must keep it. When a class has no explicit serialVersionUID, the JVM computes one from the class structure. Any change to the class changes the computed ID, which makes old data unloadable with an InvalidClassException. Declaring a fixed serialVersionUID suppresses that check; it moves the problem from “fails at load time” to “silently loads corrupted data.”

What to use instead. For persistence and interchange, JSON (Jackson, Gson) and Protocol Buffers produce formats that are independent of Java class identity. They’re readable, versionable, and language-agnostic. For caching and sessions, the same applies. If you need a Java-only binary format that’s safe and fast, look at Kryo or MessagePack with explicit schema versioning. Avoid ObjectInputStream for data from external or untrusted sources.

JEP 290 (Java 9) introduced serialization filters that let you whitelist or size-limit what ObjectInputStream will reconstruct. It reduced the attack surface but didn’t change the fundamental coupling problem.

Resource lifetime

Every InputStream, OutputStream, Reader, Writer, Channel, Selector, and Stream<Path> holds an OS resource: a file descriptor, a socket descriptor, or a directory iterator. If you don’t close them, the JVM eventually finalizes them, but finalizers are unreliable in timing. On systems with tight file descriptor limits, leaked descriptors cause java.io.IOException: Too many open files.

try-with-resources handles this. Any class that implements Closeable can appear in the resource declaration:

try (InputStream a = ...; InputStream b = ...) {
    // both a and b are closed when this block exits, even on exception
}

Resources are closed in reverse declaration order. If closing a throws and closing b also throws, the second exception is suppressed (attached to the first with addSuppressed).

The rule: if you open it, close it. If you’re unsure whether a stream was opened successfully, use try-with-resources and let the language handle the cleanup.

Questions or corrections

Found a mistake or have a question about this breakdown? Reach out directly.

Reply on X (@unkletayor)Email feedback