Skip to main content
InterviewHubPRO
Section Overview
Q19

Question 19 of 50

Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)

38%
Java Core & JVM (50 Qs)•Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)

What is the difference between Java IO (Streams) and NIO.2 (Channels, Buffers, Selectors)?

senior LevelCode ExampleState ManagementSystem DesignGolang

In Simple Words:

  • Standard Java IO (java.io): Stream-oriented and blocking. When a thread executes inputStream.read(), the thread goes into the blocked state until bytes arrive from the OS socket or disk. One thread is required per connection (Thread-per-Request).
  • Java NIO.2 (java.nio): Buffer-oriented and non-blocking. Channels transfer bytes via native OS buffers, and a single thread can monitor thousands of active network sockets using an OS event demultiplexer (Selector backed by Linux epoll or BSD kqueue).
java
// NIO.2 Non-Blocking Socket Channel:
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.bind(new InetSocketAddress(8080));
serverChannel.configureBlocking(false); // Non-blocking mode!

Selector selector = Selector.open();
serverChannel.register(selector, SelectionKey.OP_ACCEPT);

// A single selector thread handles 10,000+ idle client sockets!

Key Architectural Components:

  1. Buffer: A contiguous block of memory with position, limit, and capacity.
  2. Channel: A bidirectional pipe directly to an OS file or network socket.
  3. Selector: Registers channels to receive notification of ready states (Accept, Connect, Read, Write).