Backend Development 9 min read

Understanding Java NIO vs IO: Differences, Channels, Buffers, and Example Code

This article explains the core differences between Java NIO and traditional IO, introduces the concepts of channels and buffers, details buffer state management, and provides sample NIO code along with a comparison to Netty's processing model.

Java Captain
Java Captain
Java Captain
Understanding Java NIO vs IO: Differences, Channels, Buffers, and Example Code

First, the core differences are highlighted: NIO processes data in blocks, offering higher efficiency than the byte‑stream based IO; it uses channels and buffers instead of InputStream/OutputStream; channels are bidirectional while streams are unidirectional; buffers can be sliced and come in various types such as read‑only, direct, and indirect; and NIO employs a multiplexed, non‑blocking IO model compared to the blocking model of classic BIO.

The article then explains what a channel is: an object that simulates streams, requiring all data to pass through it, and works together with a Buffer, which acts as a container for bytes before writing to or after reading from a channel.

Next, the concept of a Buffer is described: a container object (often a byte array) that holds data to be written or read, providing structured access and tracking of read/write progress. Various Buffer types are listed, such as ByteBuffer, CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer, and DoubleBuffer.

The internal working of a Buffer is detailed with its four key properties: capacity (total length), position (next element to operate on), limit (first element that cannot be accessed, where limit ≤ capacity), and mark (a saved position). Methods like flip() , clear() , and mark() / reset() are explained for switching between write and read modes and resetting positions.

A complete NIO code example is provided, showing how to allocate a ByteBuffer, open a Selector, configure a non‑blocking ServerSocketChannel, register events, and handle accept and read operations using the buffer’s clear() , read() , and flip() methods.

public void selector() throws IOException {
    // Allocate buffer memory
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    // Open Selector for polling channel states
    Selector selector = Selector.open();
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false); // non‑blocking mode
    ssc.socket().bind(new InetSocketAddress(8080));
    ssc.register(selector, SelectionKey.OP_ACCEPT); // register accept event
    while (true) {
        Set selectedKeys = selector.selectedKeys(); // get all keys
        Iterator it = selectedKeys.iterator();
        while (it.hasNext()) {
            SelectionKey key = (SelectionKey) it.next();
            if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
                ServerSocketChannel ssChannel = (ServerSocketChannel) key.channel();
                SocketChannel sc = ssChannel.accept(); // accept client
                sc.configureBlocking(false);
                sc.register(selector, SelectionKey.OP_READ);
                it.remove();
            } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                SocketChannel sc = (SocketChannel) key.channel();
                while (true) {
                    buffer.clear();
                    int n = sc.read(buffer); // read data
                    if (n <= 0) {
                        break;
                    }
                    buffer.flip();
                }
                it.remove();
            }
        }
    }
}

Finally, the article compares NIO with Netty’s workflow: NIO requires manual creation of ByteBuffer and handling of OP_ACCEPT/OP_READ events, while Netty abstracts these details with EventLoopGroup, ServerBootstrap, and ByteBuf, simplifying accept handling and providing built‑in decoders such as FixedLengthFrameDecoder to address TCP packet fragmentation.

JavaNIONettyioChannelsBuffers
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.