How does a blocking java.net.Socket differ from a SocketChannel, and when does each fit now that virtual threads exist?
answer
- streams versus buffers
- blocking by default, switchable
- only channels join a Selector
- interrupt closes the channel
- virtual threads make both cheap
basics
~20 sA Socket moves bytes through blocking streams; a SocketChannel moves ByteBuffers, can run non-blocking under a Selector, and is closed by an interrupt on any thread. On virtual threads both block cheaply, so pick channels for buffers, selectors or Unix-domain sockets.
solid answer
~40 s`Socket` gives you an `InputStream`/`OutputStream` pair and always blocks the caller; it cannot join a `Selector`. A `SocketChannel` moves `ByteBuffer`s (with scatter/gather), starts in blocking mode but can switch with `configureBlocking(false)` and be multiplexed by a `Selector`, and is an `InterruptibleChannel`: an interrupt closes it and throws `ClosedByInterruptException`, while on a platform thread an interrupt leaves a plain `Socket` read blocked. The socket side has `setSoTimeout()`; a channel's `read()` has no timeout. On virtual threads (final in JDK 21) a blocking call on either releases the platform thread, so thread-per-connection code can keep `Socket` streams. I'd choose a channel for direct buffers, `transferTo()` into the socket, Unix-domain sockets, or one event loop owning many connections; `socket()` bridges the two.
code
java · 37 linesimport java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ChannelEcho {
public static void main(String[] args) throws IOException {
try (ServerSocketChannel server = ServerSocketChannel.open().bind(new InetSocketAddress(9001));
ExecutorService perConnection = Executors.newVirtualThreadPerTaskExecutor()) {
while (true) {
SocketChannel channel = server.accept(); // blocking mode is the default
perConnection.submit(() -> echo(channel));
}
}
}
static void echo(SocketChannel channel) {
ByteBuffer buffer = ByteBuffer.allocateDirect(8192);
try (channel) {
while (channel.read(buffer) != -1) {
buffer.flip();
while (buffer.hasRemaining()) {
channel.write(buffer);
}
buffer.clear();
}
} catch (ClosedByInterruptException e) {
System.err.println("interrupted; the channel is now closed");
} catch (IOException e) {
System.err.println("connection ended: " + e);
}
}
}go deeper
Recall that Socket works with streams and always blocks, while SocketChannel works with ByteBuffers, starts in blocking mode and can be switched to non-blocking for a Selector.
Explain the interrupt and close differences: ClosedByInterruptException and AsynchronousCloseException on a channel, SocketException on a socket, and why a platform-thread interrupt leaves a socket read blocked.
Choose per workload: blocking code on virtual threads with either API, channels for buffers, transferTo and Unix-domain sockets, selectors for event loops, and know how to put a timeout on each.
Decide a team default for network code on JDK 21 and later, weighing simpler blocking code against existing event-loop frameworks, observability, and the cost of mixing models.
## Two APIs for one TCP connection `java.net.Socket` (JDK 1.0) exposes a connection as an `InputStream` and an `OutputStream`. `java.nio.channels.SocketChannel` (JDK 1.4) exposes it as a **selectable channel** that reads into and writes from `ByteBuffer`s. Since JDK 13 the `Socket` implementation shares NIO's internal infrastructure, so the difference is the programming model, not two separate network stacks. ## Side by side | | `Socket` | `SocketChannel` | |---|---|---| | Data | `byte[]` through streams | `ByteBuffer`, plus scatter/gather over arrays of buffers | | Blocking | always blocks the caller | blocking by default; after `configureBlocking(false)` a `read()` returns `0` when nothing is ready | | Multiplexing | cannot be registered with a `Selector` | registers with a `Selector` in non-blocking mode | | Read timeout | `setSoTimeout()` on the stream | none on `read()`; `SO_TIMEOUT` is not a channel option | | Interrupt, platform thread | no effect on a blocked read | closes the channel; `ClosedByInterruptException` | | Interrupt, virtual thread | wakes, closes the socket; `SocketException` | closes the channel; `ClosedByInterruptException` | | Close from another thread | `SocketException` | `AsynchronousCloseException` | | Unix-domain sockets | `connect()` rejects them with `IllegalArgumentException` | `SocketChannel.open(StandardProtocolFamily.UNIX)`, since JDK 16 | ## Interrupts and asynchronous close - `SocketChannel` is an `InterruptibleChannel`. Interrupting a thread blocked in one of its I/O operations closes the channel, throws `ClosedByInterruptException` and leaves the interrupted status set. If the status is already set when the thread starts a blocking operation, the channel is closed at once. - Closing the channel from another thread makes the blocked thread throw `AsynchronousCloseException`. Shutting down the input side from another thread makes a blocked read return `-1` instead. - A plain `Socket` is interruptible only when the caller is a virtual thread (specified in JDK 19 under the preview, final in JDK 21) or the socket belongs to a channel. On a platform thread an interrupt does nothing to a blocked read; only `close()` frees it. - Either way, an interrupt is not a way to cancel one read and keep the connection: whenever it works, the connection is gone. ## Bridging the two - `SocketChannel.socket()` returns an adapter `Socket` whose streams delegate to the channel. Its `setSoTimeout()` applies to those streams only, and they throw `IllegalBlockingModeException` while the channel is in non-blocking mode. - `Socket.getChannel()` returns `null` unless the socket was created by `SocketChannel.open()` or `ServerSocketChannel.accept()`. - For a Unix-domain channel, `socket()` throws `UnsupportedOperationException`, because there is no `Socket` view of such a connection. ## Timeouts on each side - **Connecting.** `Socket.connect(address, millis)` takes a timeout. `SocketChannel.connect(address)` takes none: in blocking mode it waits until the connection is made or fails. To bound it, connect through the adapter with `channel.socket().connect(address, millis)`, or start a non-blocking connect and wait for `OP_CONNECT` with `Selector.select(timeout)` before calling `finishConnect()`. - **Reading.** `Socket` has `setSoTimeout()`. A channel's `read()` has no timeout, so read through the adapter's stream, wait on a selector with a timeout, or close the channel from another thread at the deadline. - **Writing.** Neither `SO_TIMEOUT` nor any channel method bounds a blocking write; it waits until it can proceed, fails, or the connection is closed. ## Choosing now that virtual threads exist - **Blocking code on virtual threads, either API.** On JDK 21 and later a blocking read or write on a `Socket` or on a blocking `SocketChannel` releases the platform thread while it waits (JEP 444). If the code is already written against streams, keep `Socket`. - **A blocking `SocketChannel` on a virtual thread** when you want `ByteBuffer`s: direct buffers, scatter/gather, `FileChannel.transferTo()` into the socket, or Unix-domain sockets. - **Non-blocking channels with a `Selector`** when one event loop must own many connections: an event-loop framework, readiness-driven protocol state machines, or code that must also run on releases before JDK 21. - **Not for memory alone.** JEP 444 expects the heap use of thread-per-request code and of asynchronous code to be roughly similar, so a selector is not automatically lighter. - **Pinning.** On JDK 21 to 23 a virtual thread that blocked inside a `synchronized` block kept its carrier; JDK 24 removed that for `synchronized` (JEP 491), so JDK 25 and 27 behave the same here.
- How do you put a read timeout on a blocking SocketChannel?Its `read()` takes no timeout and `SO_TIMEOUT` is not a channel option. Read through the adapter's stream after `channel.socket().setSoTimeout(ms)`, switch to non-blocking mode and wait with `Selector.select(timeout)`, or have another thread close the channel at the deadline, which makes the blocked read throw `AsynchronousCloseException`.
- With virtual threads available, is a Selector-based server obsolete?No. Virtual threads make the blocking style scale, which removes the main reason most applications wrote selector loops. A selector still fits an event-loop framework, readiness-driven protocols, code that must run before JDK 21, or designs where one thread owns all connection state. Memory alone is not the reason: JEP 444 expects heap use to be roughly similar.
- What happens if a thread whose interrupted status is already set calls read() on a SocketChannel?In blocking mode the channel is closed at once and the call throws `ClosedByInterruptException`, with the status still set; the rule covers blocking operations only, so in non-blocking mode the read simply returns. A thread that restores an interrupt with `Thread.currentThread().interrupt()` and then carries on with blocking channel I/O closes its own channel.
- A SocketChannel is in non-blocking mode as soon as it is opened.
- Interrupting a thread blocked in SocketChannel.read() cancels the read but keeps the connection.
- Any Socket can be registered with a Selector through getChannel().
- On virtual threads a blocking Socket still holds an OS thread for every connection.
- Calling socket().setSoTimeout() on a channel's adapter also bounds channel.read().
- java.nio.channels.SocketChannel
- Java 1.4
- java.nio.channels.Selector
- Java 1.4
- Unix-domain socket channels
- Java 16
- Virtual threads
- Java 21pre-release 19
Assumes JDK 27; virtual threads are final since JDK 21, and blocking inside synchronized code stopped pinning them in JDK 24, so JDK 25 behaves the same.
context
- SocketChannel (Java SE 27 & JDK 27)docs.oracle.com
- Socket (Java SE 27 & JDK 27)docs.oracle.com
- JEP 444: Virtual Threadsopenjdk.org