Skip to main content

Java NIO (New I/O)

Core NIO Components #

Buffers #

  • Buffer: The base class for all buffers with position, limit, and capacity management
  • ByteBuffer: Byte buffer implementation with direct and heap variants
  • CharBuffer: Character buffer for text processing
  • IntBuffer: Integer buffer implementation
  • LongBuffer: Long buffer implementation
  • FloatBuffer: Float buffer implementation
  • DoubleBuffer: Double buffer implementation
  • ShortBuffer: Short buffer implementation

Channels #

Selectors and Multiplexing #

Charsets and Encoding #

File I/O (NIO.2) #

File Attributes #

Asynchronous I/O #

Memory-Mapped Files #

Utilities and Supporting Classes #

NIO Architecture Overview #

Application
    ↓
Buffers (ByteBuffer, CharBuffer, etc.)
    ↓
Channels (FileChannel, SocketChannel, etc.)
    ↓
Selectors (I/O Multiplexing)
    ↓
Operating System (epoll, kqueue, IOCP)

Performance Characteristics #

ComponentReadWriteRandom AccessMemory Mapping
FileChannelO(1)O(1)O(1)Yes
SocketChannelO(1)O(1)N/ANo
MappedByteBufferO(1)O(1)O(1)Yes
HeapByteBufferO(1)O(1)O(1)No
DirectByteBufferO(1)O(1)O(1)Yes

Key Features #

  1. Non-blocking I/O: Enable high-performance, scalable network applications
  2. Buffer-oriented: All I/O operations work with buffers for efficiency
  3. Selector-based multiplexing: Single thread can handle thousands of connections
  4. Memory mapping: Direct memory access to files for zero-copy I/O
  5. Character set support: Comprehensive encoding/decoding framework
  6. File system abstraction: Cross-platform file system operations

When to Use NIO #

Use NIO when:

  • Building high-performance network servers
  • Handling thousands of simultaneous connections
  • Need non-blocking I/O operations
  • Working with large files and memory mapping
  • Requiring cross-platform file system operations

Use traditional I/O when:

  • Simple file operations on small files
  • Sequential processing of text files
  • Blocking I/O is acceptable for your use case
  • Working with character streams (Reader/Writer)

NIO vs Traditional I/O #

FeatureTraditional I/ONIO
BlockingYesOptional
BufferingStream-basedBuffer-based
PerformanceGoodExcellent for many connections
ScalabilityLimitedHigh (thousands of connections)
API ComplexitySimpleMore complex
Memory MappingNoYes
Selector SupportNoYes
Character EncodingLimitedComprehensive