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 executesinputStream.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 (Selectorbacked by Linuxepollor BSDkqueue).
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:
- Buffer: A contiguous block of memory with
position,limit, andcapacity. - Channel: A bidirectional pipe directly to an OS file or network socket.
- Selector: Registers channels to receive notification of ready states (Accept, Connect, Read, Write).