Blocking vs Non-Blocking I/O in Java: Streams, NIO Channels and Buffers
How blocking java.io sockets tie a thread to each connection, why thread pools cap a blocking server, and how java.nio channels, ByteBuffer and non-blocking mode let one thread serve many connections. Buffer flip and compact, and where virtual threads change the trade-off.
kvi5hnuCode Sprout team member8 min readOn this page
Part 6 looks at the main alternative to virtual threads for scalable I/O: reactive programming. Reactive libraries such as Project Reactor, RxJava and Vert.x rest on three ideas: they're non-blocking, event-driven and asynchronous. They implement the Reactive Manifesto (first published in 2013, revised in 2014), which describes reactive systems as responsive, resilient, elastic and message-driven. To judge when reactive code is worth its cost now that virtual threads exist, you need to understand what those ideas solve. This article starts at the bottom, with the difference between blocking and non-blocking I/O.
Blocking I/O
With java.io, a read waits until data arrives. socket.getInputStream().read(), BufferedReader.readLine() and ServerSocket.accept() all block the calling thread: it can do nothing else until the operation completes. That's what makes blocking code easy to write. A request handler reads, computes and writes, top to bottom, like any other method.
The cost is that a waiting thread is still a thread. A blocking server needs one thread for each connection it serves at the same time:
- With one thread, a slow client blocks every other client.
- With a pool of N platform threads, N slow clients block everyone else. Platform threads are expensive (article 3), so N is typically a few hundred.
- With virtual threads, a thread per connection is cheap, so the limit mostly disappears (article 11).
Non-blocking I/O
java.nio (added in Java 1.4) offers a different model. A channel in non-blocking mode never waits: read returns immediately with however many bytes are available, possibly zero, and write writes as many as fit in the OS buffer. A thread can then serve many connections by trying each one and moving on. Article 43 adds the missing piece, the selector, which tells the thread which channels are ready so it doesn't have to poll.
NIO replaces streams with channels and buffers:
java.io | java.nio |
|---|---|
InputStream / OutputStream, one byte or array at a time | ReadableByteChannel / WritableByteChannel, reading into and writing from a ByteBuffer |
ServerSocket, Socket | ServerSocketChannel, SocketChannel (blocking or non-blocking) |
| always blocking | configureBlocking(false) for sockets |
FileInputStream | FileChannel, with memory-mapped files and transferTo |
Buffers
A ByteBuffer is a fixed-size array with three indexes: capacity (its size), limit (the end of the usable region) and position (where the next read or write happens). Channels read into a buffer at its position, and write from it between position and limit.

Two methods switch between filling and draining:
flip()sets limit to the current position and position to 0: "I've finished writing, now read what I wrote".compact()moves the unread bytes to the start and sets position after them: "keep what I haven't consumed, and let me write more after it". It's how a server keeps half a request that arrived in one read and waits for the rest.
There's also clear() (start over, discarding everything) and rewind() (read again from 0). Forgetting flip() before writing a buffer out is the classic NIO bug: position is at the end of your data and the limit is the capacity, so write sends the unused bytes between them instead of your data.
The three models in one program
The program shows buffer mechanics, then runs the same blocking request handler under three servers: one thread, a pool of two threads, and a virtual thread per connection. Two slow clients (600 ms) connect first, followed by four fast ones (50 ms). Finally, it reads from a non-blocking channel.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Consumer;
public class Solution {
// ---------- 1. Buffer mechanics ----------
static String state(ByteBuffer b) {
return "position=" + b.position() + " limit=" + b.limit() + " capacity=" + b.capacity();
}
static void buffers() {
ByteBuffer buf = ByteBuffer.allocate(16);
System.out.println("1. new buffer: " + state(buf));
buf.put("LIS-OSL".getBytes(StandardCharsets.US_ASCII));
System.out.println(" after put 7 bytes: " + state(buf));
buf.flip(); // switch from writing to reading
System.out.println(" after flip: " + state(buf));
byte[] first3 = new byte[3];
buf.get(first3);
System.out.println(" read \"" + new String(first3, StandardCharsets.US_ASCII) + "\": " + state(buf));
buf.compact(); // keep the unread 4 bytes, write after them
System.out.println(" after compact: " + state(buf));
}
// ---------- 2. Blocking servers: one thread vs pools vs virtual threads ----------
static void handle(Socket socket) {
try (socket;
var in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
var out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8)) {
String request = in.readLine(); // blocks until a line arrives
Thread.sleep(request.equals("slow") ? 600 : 50); // a slow or fast back-end call
out.println("quote for " + request);
} catch (IOException | InterruptedException e) {
// the client went away; nothing to do in a demo
}
}
/** Accepts connections forever; dispatch decides which thread handles each one. */
static ServerSocket startServer(Consumer<Socket> dispatch) throws IOException {
ServerSocket server = new ServerSocket(0);
Thread.ofPlatform().daemon().start(() -> {
while (true) {
try {
dispatch.accept(server.accept()); // accept() blocks too
} catch (IOException e) {
return; // server closed
}
}
});
return server;
}
static long request(int port, String what) throws IOException {
long start = System.nanoTime();
try (var socket = new Socket("localhost", port);
var in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
var out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8)) {
out.println(what);
in.readLine();
}
return (System.nanoTime() - start) / 1_000_000;
}
/** Two slow clients first, then four fast ones; reports whether the fast ones had to wait. */
static void load(String label, Consumer<Socket> dispatch) throws Exception {
try (ServerSocket server = startServer(dispatch);
ExecutorService clients = Executors.newVirtualThreadPerTaskExecutor()) {
int port = server.getLocalPort();
List<Future<Long>> slow = List.of(clients.submit(() -> request(port, "slow")),
clients.submit(() -> request(port, "slow")));
Thread.sleep(50); // let the slow requests arrive first
List<Future<Long>> fast = new ArrayList<>();
for (int i = 0; i < 4; i++) fast.add(clients.submit(() -> request(port, "fast")));
long worstFast = 0;
for (Future<Long> f : fast) worstFast = Math.max(worstFast, f.get());
for (Future<Long> f : slow) f.get();
System.out.println(" " + label + (worstFast > 500 ? "fast requests waited behind slow ones"
: "fast requests were not delayed"));
}
}
// ---------- 3. A non-blocking read returns at once ----------
static void nonBlockingRead() throws IOException {
try (ServerSocket server = new ServerSocket(0);
SocketChannel channel = SocketChannel.open(new InetSocketAddress("localhost", server.getLocalPort()));
Socket peer = server.accept()) {
channel.configureBlocking(false);
ByteBuffer buf = ByteBuffer.allocate(64);
System.out.println("3. read with no data waiting: " + channel.read(buf) + " bytes");
peer.getOutputStream().write("ok\n".getBytes(StandardCharsets.UTF_8));
int n;
while ((n = channel.read(buf)) == 0) Thread.onSpinWait(); // polling: what a Selector avoids
System.out.println(" after the peer wrote: " + n + " bytes");
}
}
public static void main(String[] args) throws Exception {
buffers();
System.out.println("2. two slow requests, then four fast ones:");
load("single thread: ", Solution::handle);
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
load("pool of 2 threads: ", socket -> pool.submit(() -> handle(socket)));
}
try (ExecutorService virtual = Executors.newVirtualThreadPerTaskExecutor()) {
load("virtual threads: ", socket -> virtual.submit(() -> handle(socket)));
}
nonBlockingRead();
}
}
Output:
1. new buffer: position=0 limit=16 capacity=16
after put 7 bytes: position=7 limit=16 capacity=16
after flip: position=0 limit=7 capacity=16
read "LIS": position=3 limit=7 capacity=16
after compact: position=4 limit=16 capacity=16
2. two slow requests, then four fast ones:
single thread: fast requests waited behind slow ones
pool of 2 threads: fast requests waited behind slow ones
virtual threads: fast requests were not delayed
3. read with no data waiting: 0 bytes
after the peer wrote: 3 bytes
- Buffers. The positions match the diagram. After
compact, the buffer holds-OSLat the front and is ready for more bytes, for example the rest of a request. - Blocking servers. With one thread, the fast clients waited for both slow requests. With two pool threads, both threads were busy with slow requests, so the fast clients still waited: a pool only moves the limit from 1 to N. With virtual threads, every connection got its own thread and no one waited.
- Non-blocking read. With no data available,
readreturned 0 immediately instead of waiting. The demo then spun until the data arrived, which wastes a CPU core. A real non-blocking server asks aSelectorinstead (article 43).
What non-blocking I/O buys, and what it costs
Before virtual threads, non-blocking I/O was the only way to serve tens of thousands of mostly idle connections from one JVM. A few threads, typically one per core, could serve them all. Netty, Vert.x, Undertow and Spring WebFlux's default server are all built on it.
The price is paid in the code that sits on top:
- A request is no longer handled by one method running top to bottom. The handler is called piecemeal, whenever more bytes arrive, so its progress must be stored in a per-connection state object.
- Nothing on an I/O thread may block. One blocking database call on an event-loop thread stalls every connection that thread serves (article 44).
- Business code needs asynchronous APIs for everything it waits for: callbacks, futures, or reactive streams.
Virtual threads remove most of the reason to pay that price for request/response code. The JDK itself runs blocking-style socket code on top of non-blocking sockets and a poller (article 23): you write the blocking version, and the runtime gets the scalability of the non-blocking one.
What's current
- Since Java 13 and 15 (JEPs 353 and 373),
Socket,ServerSocketandDatagramSocketare implemented on top of NIO, which is what lets virtual threads unmount when they block on them. - File I/O is still blocking at the OS level. A virtual thread doing file I/O temporarily pins its carrier, and the scheduler compensates by adding a carrier (article 14).
- NIO's core API has barely changed since Java 7 (NIO.2 added
AsynchronousSocketChanneland thePath/FilesAPI). It remains the foundation of the networking libraries mentioned above.
Common questions
Is non-blocking I/O faster than blocking I/O? Not per request. A single read takes about the same time either way. The gain is in resources: fewer threads for the same number of connections. With virtual threads, blocking code gets most of the same benefit.
What's the difference between non-blocking and asynchronous I/O?
Non-blocking calls return immediately with whatever they could do, and you call again later, usually when a selector says the channel is ready. Asynchronous calls (AsynchronousSocketChannel) start an operation and notify you through a callback or Future when it completes. Both avoid tying up a thread while waiting.
Why does read return 0 instead of blocking?
Because the channel is in non-blocking mode and no bytes are available yet. -1 means the peer closed the connection, and a positive number is the count of bytes read.
Should I write servers on raw NIO today? Rarely. Use a library such as Netty if you need an event loop, or write blocking code on virtual threads. Raw NIO is worth knowing because everything else is built on it.
Summary
- Blocking
java.iocalls hold their thread until the operation completes, so a blocking server needs one thread per concurrent connection, and a pool caps how many connections it serves at once. - Non-blocking NIO channels return immediately, with zero bytes if nothing is available, so one thread can serve many connections.
- A
ByteBufferhas capacity, limit and position.flip()switches from filling to draining, andcompact()keeps unread bytes and makes room for more. - Non-blocking servers scale with few threads but turn handlers into piecemeal state machines that must never block. Virtual threads get similar scalability with blocking code.
Practice questions
A blocking server uses a pool of 200 platform threads. 200 clients connect and send nothing. What happens to client 201?
Answer
Its connection is accepted by the OS, but no thread is free to read from it: all 200 threads are blocked waiting for data from idle clients. Client 201 waits until one of them sends a request and finishes, or times out. With virtual threads, or with non-blocking I/O, idle connections don't occupy threads.
This code is meant to write the bytes it just put into a buffer to a channel, but the receiver gets 54 zero bytes instead of the message. Why?
ByteBuffer buf = ByteBuffer.allocate(64);
buf.put("quote 212\n".getBytes(StandardCharsets.UTF_8));
channel.write(buf);
Answer
After put, the position is at the end of the data (10) and the limit is 64, so write sends the 54 bytes between position and limit, which are zeros, not the message. Call buf.flip() before write so that position is 0 and limit is 10.
A non-blocking SocketChannel.read(buf) returns 0 in a loop that calls it repeatedly. What's wrong with that design, and what should replace it?
Answer
It's busy-polling: the thread burns CPU checking a channel that has no data, and with many channels it would check them all constantly. Register the channels with a Selector and call select(), which sleeps until the OS reports that some channels are ready, and then read only those.
Previous: Scoped Values With Structured Concurrency: Inheritance, Use Cases and Migrating From ThreadLocal

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.