Introduction to Java NIO: Buffers, Channels, and Selectors
This article provides a comprehensive overview of Java NIO, explaining the differences between BIO and NIO, the concepts of synchronous/asynchronous and blocking/non‑blocking I/O, and detailing the usage and implementation of Buffers, Channels, and Selectors with code examples.
1. Introduction to Java NIO
Java NIO (New I/O) addresses the shortcomings of traditional BIO (Blocking I/O) such as blocking behavior and low efficiency. BIO is synchronous and blocking, while NIO introduces synchronous non‑blocking, asynchronous blocking, and asynchronous non‑blocking models.
The article is organized into four chapters that focus on the usage and source‑code analysis of Java NIO's Buffer, Channel, and Selector.
2. Buffer
A Buffer is a container for storing primitive data types, similar to an array. It is an abstract class with seven direct subclasses (IntBuffer, CharBuffer, ShortBuffer, LongBuffer, FloatBuffer, DoubleBuffer, ByteBuffer).
Buffers operate on four key values: capacity, limit, position, and mark, with the relationship 0 ≤ mark ≤ position ≤ limit ≤ capacity.
Common Buffer methods include capacity() , limit() , position() , mark() , clear() , and others such as wrap() , put() , get() , rewind() , and allocateDirect() . The article explains each method’s purpose and behavior.
3. Channel
Channels are the transport mechanism that moves data from Buffers to their destination. The Channel interface has many sub‑interfaces (e.g., AsynchronousChannel, ReadableByteChannel, WritableByteChannel, ScatteringByteChannel, GatheringByteChannel, ByteChannel, SeekableByteChannel, NetworkChannel, MulticastChannel, InterruptibleChannel) each serving specific I/O functions.
FileChannel, a concrete implementation, provides methods for reading, writing, and mapping files. The article details methods such as write(ByteBuffer) , read(ByteBuffer) , write(ByteBuffer[], int, int) , and positional read/write variants.
4. Selector
A Selector enables a single thread to monitor multiple channels for readiness, implementing I/O multiplexing. It works together with SelectionKey and SelectableChannel to register channels, retrieve ready keys, and process I/O events.
5. Summary
Java NIO leverages I/O multiplexing and synchronous non‑blocking operations, allowing a small number of threads to manage many channels efficiently, thereby reducing CPU and memory consumption.
6. References
https://my.oschina.net/u/3824443/blog/2875430
《NIO与Socket编程技术指南》
New Oriental Technology
Practical internet development experience, tech sharing, knowledge consolidation, and forward-thinking insights.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.