Lab 07: NIO.2 Channels & ByteBuffer

Objective

Master Java NIO for high-performance I/O: ByteBuffer for direct memory manipulation, FileChannel with scatter/gather I/O, MappedByteBuffer for memory-mapped files, Path glob patterns, and designing a binary catalog format with header + payload.

Background

Java NIO (New I/O, java.nio) replaced blocking stream I/O for high-throughput scenarios. ByteBuffer is a fixed-capacity container with a position/limit/capacity model — you write until position reaches limit, then flip() to switch to read mode. FileChannel supports scatter (read into multiple buffers) and gather (write from multiple buffers) I/O in a single syscall.

Time

30 minutes

Prerequisites

  • Practitioner Lab 06 (File I/O & NIO.2)

Tools

  • Docker: zchencow/innozverse-java:latest


Lab Instructions

Steps 1–8: ByteBuffer read/write, flip/rewind, FileChannel scatter-gather, MappedByteBuffer, Path glob, binary product catalog, checksums, Capstone

💡 MappedByteBuffer is zero-copy. Reading from a memory-mapped file means the OS maps the file's page cache directly into your process's address space — no data is copied from kernel space to user space. For read-heavy workloads on large files (database files, log archives), this is dramatically faster than FileInputStream. SQLite, Elasticsearch, and Kafka all use memory-mapped files internally.

📸 Verified Output:


Summary

API
Use for

ByteBuffer.allocate(n)

Heap-backed buffer

ByteBuffer.allocateDirect(n)

Off-heap (faster native I/O)

buf.flip()

Switch write→read mode

fc.write(ByteBuffer[])

Gather: multi-buffer write

fc.read(ByteBuffer[])

Scatter: multi-buffer read

fc.map(READ_WRITE, 0, size)

Memory-mapped file

Files.newDirectoryStream(dir, "*.csv")

Glob filter

Further Reading

Last updated