实际上高并发的网络服务基本都是用 NIO,而且一般不直接用,是用 Netty。AIO 用得很少,因为在 Linux 上它其实是用线程池模拟出来的,性能没有优势。
English PitchEnglish · ~60s
BIO, NIO, and AIO represent three different concurrency models for handling I/O in Java. With BIO, a thread blocks on every read or write, forcing a thread-per-connection model that breaks down under thousands of mostly idle sockets due to memory and context-switching overhead. NIO solves this with non-blocking channels multiplexed onto a Selector—backed by epoll on Linux—so a single thread manages thousands of connections, though the app thread still copies data synchronously. AIO is asynchronous I/O: the app initiates an operation and returns immediately, receiving a completion callback after the data is copied. In production, however, we almost always use NIO via Netty, since Java AIO is emulated with a thread pool on Linux and rarely outperforms NIO.
A Java NIO Buffer is a fixed-size memory block managed by three pointers: capacity is its immutable total size, position is the next index to read or write, and limit is the boundary you cannot pass. While writing, position advances toward capacity; calling flip switches to read mode by setting limit to the current position and resetting position to zero so you read only what was written. Afterward, clear resets pointers for a fresh write, while compact shifts unread partial data to the front before appending more. In production, forgetting flip is the classic bug, and high-throughput services reuse pooled direct buffers to avoid extra heap copies.
Key terms:position, limit, capacity, flip vs compact, direct ByteBuffer
Likely follow-up: "Why do direct buffers avoid an extra memory copy during I/O, and what makes them expensive to allocate?"
A Selector lets one thread monitor many non-blocking channels by registering each channel's interest set—accept, connect, read, or write—and blocking in select until a channel is ready. The event loop processes ready SelectionKeys and removes each key from the selected-key set afterward so it is not re-handled, while other threads call wakeup() to unblock select() when registering new channels or tasks. Because TCP is a byte stream and non-blocking I/O never guarantees full completion, reads may return half a message and writes may hit a full kernel send buffer. You must buffer incoming bytes for framing and hold unsent bytes under temporary OP_WRITE registration, which is why teams rely on Netty rather than raw NIO.
底层的实现上,默认用的是 JDK 的 NIO,在 Linux 上也可以换成 Netty 自己实现的 epoll 传输,性能更好一些。
English PitchEnglish · ~50s
Netty uses the multi-threaded master-slave Reactor pattern with two EventLoopGroups: Boss and Worker. The Boss group only listens on the server socket, accepts incoming connections, and hands each new channel off to a Worker EventLoop, which handles all reads, writes, and pipeline callbacks for that connection. Each EventLoop is a single-threaded loop processing I/O events and queued tasks, and every channel stays pinned to one EventLoop for its entire lifetime. That thread confinement means per-connection handler state needs no locks, while cross-thread writes are safely marshaled back onto the channel's EventLoop queue.
A ChannelPipeline is a per-connection chain of responsibility that organizes ChannelHandlers in order for decoding, authentication, business logic, and encoding. Inbound events—like incoming bytes, connection lifecycle changes, and inbound exceptions—flow head-to-tail through inbound handlers, while outbound operations like write, flush, and close travel tail-to-head through outbound handlers. Each handler must explicitly forward events, otherwise propagation stops there. Two practical details matter most: ctx.write starts from the current handler toward the head, whereas channel.write starts at the tail so all encoders run; and only stateless or thread-safe handlers without per-connection mutable state should be marked @Sharable, since stateful ones like ByteToMessageDecoder are not thread-safe across EventLoops.
Key terms:ChannelPipeline, inbound vs outbound propagation, ctx.write vs channel.write, @Sharable
Likely follow-up: "Why does ctx.write() sometimes skip an encoder that was added to the pipeline, and how do outbound exceptions get reported compared to inbound ones?"
追问3 个
入站和出站 Handler 的添加顺序有什么讲究?
入站按添加顺序执行,出站按相反顺序执行。解码器要在业务 Handler 之前;编码器只要在调用 write 的位置的 head 一侧即可。
Blocking an EventLoop thread is the fastest way to stall a Netty service. Because one EventLoop multiplexes hundreds or thousands of connections sequentially on a single thread, any blocking call—like JDBC queries, synchronous HTTP calls, lock waits, or heavy CPU work—freezes I/O, responses, and heartbeats for every connection on that loop. With Worker pools sized around twice the CPU cores, stalling just a few threads makes the server unresponsive while CPU looks deceptively low. The fix is offloading blocking work to a dedicated, bounded business executor—or using async clients end to end—and letting Netty marshal writeAndFlush back to the EventLoop.
Key terms:EventLoop starvation, non-blocking pipeline, bounded business executor, backpressure
Likely follow-up: "How would you detect EventLoop blocking in production, and why should the business thread pool use a bounded queue?"
Netty's ByteBuf fixes several ergonomic and performance limits of JDK ByteBuffer. Instead of one shared position requiring flip, ByteBuf separates readerIndex and writerIndex, expands automatically up to maxCapacity, supports zero-copy views via CompositeByteBuf and slices, and adds reference counting with jemalloc-style pooling. For buffer types, direct off-heap buffers avoid an extra heap-to-native copy during socket I/O, while heap buffers expose a backing byte[] for business processing. Because direct memory is expensive to allocate, Netty defaults to pooled direct buffers via ctx.alloc() on I/O paths—dramatically cutting GC and allocation overhead, with the trade-off that forgetting to release leaks native memory.
Key terms:readerIndex / writerIndex, PooledByteBufAllocator, direct vs heap memory, CompositeByteBuf
Likely follow-up: "Why should you allocate buffers with ctx.alloc().buffer() instead of Unpooled.buffer(), and how do you guard against unbounded ByteBuf growth?"
Because pooled off-heap ByteBufs cannot wait on JVM GC, Netty manages their lifecycle with explicit reference counting: buffers start at 1, retain increments, release decrements, and hitting zero returns the memory to the pool. The ownership rule is simple—whoever consumes a buffer last must release it. Forwarding an inbound message or calling ctx.write hands off responsibility, whereas consuming locally requires release, and passing a buffer to another thread requires retain first. Leaks show up as steadily climbing RSS or OutOfDirectMemoryError with a healthy heap. To diagnose them, inspect Netty direct-memory metrics and reproduce with ResourceLeakDetector set to PARANOID, which uses weak references to log the exact allocation and access stacks.
Likely follow-up: "Why don't Netty direct-memory leaks show up clearly in a standard JVM heap dump, and why isn't PARANOID leak detection left on in production?"
Because TCP is a byte stream with no message boundaries, one read can deliver half a packet or several packets merged together, so the application layer must handle framing. Netty provides built-in frame decoders—fixed-length, delimiter-based, line-based, and most commonly LengthFieldBasedFrameDecoder, which reads a header length prefix to extract each payload. All extend ByteToMessageDecoder, buffering incoming bytes per connection and forwarding only complete frames down the pipeline. In production, always set a strict maxFrameLength to block OOM attacks from huge length headers, and never mark frame decoders Sharable because they hold per-connection state.