No description
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
# Java高并发核心编程. 卷1, NIO、Netty、Redis、ZooKeeper
## 【One-Line Pitch】
A practical, code-driven guide for Java developers who want to master high-concurrency network programming—covering NIO fundamentals, Netty's architecture and codecs, HTTP connection management, and the ZooKeeper primitives that underpin distributed systems. Read this if you're building high-throughput servers, microservices, or IM systems and need to move beyond basic blocking I/O.
## 【Book Arc】
- **Opening (~0%–6%)**: Starts with the pain point of synchronous blocking I/O—threads stuck waiting for kernel buffers—then introduces NIO's core abstractions: Buffer (capacity, position, limit, mark), Channel, and Selector. Includes a file-transfer example over SocketChannel to show NIO in action.
- **Early (~6%–19%)**: Traces the evolution from Connection Per Thread to Reactor patterns, then pivots to Netty. Walks through server bootstrap setup, parent vs. child channel pipelines, ChannelInitializer usage, and the lifecycle of ChannelInboundHandler—with concrete code for an Echo server and discard server.
- **Early–Middle (~19%–38%)**: Dives deep into Netty's data layer: ByteBuf's three key properties (readerIndex, writerIndex, maxCapacity), heap vs. direct buffers, Unpooled factories, and shallow copies (slice, duplicate) with their reference-counting pitfalls. Then covers codecs: ByteToMessageDecoder, ReplayingDecoder for stateful decoding, LengthFieldBasedFrameDecoder's five parameters, and CombinedChannelDuplexHandler for pairing encoders/decoders.
- **Middle (~38%–50%)**: Builds a complete IM system with Protobuf serialization—defining message schemas, handling login requests, routing single chats by userID (not sessionID, since users may have multiple sessions), and adding heartbeat handlers with IdleStateHandler for client-server liveness detection.
- **Middle–Late (~50%–63%)**: Shifts to HTTP: request/response headers, chunked transfer encoding, keep-alive semantics across HTTP/1.0 and 1.1, and the rationale for connection pooling in microservice architectures (Nginx + Spring Cloud). Includes practical HttpClient patterns with global pooled instances and idle-check scheduling.
- **Late (~63%–end)**: Covers WebSocket integration with Netty (WebSocketServerProtocolHandler handling handshake and control frames) and introduces ZooKeeper as the distributed-systems foundation—the low-level primitives (coordination, consistency, availability) that developers would otherwise struggle to implement themselves.
## 【Key Takeaways】
- **Synchronous blocking I/O is the root problem** (Opening): A thread issuing a read() system call blocks until data arrives in the kernel buffer and is copied to user space—wasting threads on idle waits. This motivates everything that follows: NIO, Reactor patterns, and Netty.
- **NIO Buffer is a state machine, not just a byte array** (Opening): capacity is fixed at allocation; position shifts with read/write mode; limit and mark control how much you can access. Misunderstanding these four properties is the #1 source of NIO bugs.
- **Connection Per Thread doesn't scale** (Early): One thread per socket means new connections queue behind slow handlers, tanking throughput. The Reactor pattern—event demultiplexing via Selector with handler dispatch—is the architectural fix, and Netty's sub-reactor model (multiple selectors, each with its own thread) is the production-grade refinement.
- **Netty pipelines separate transport from business logic** (Early): Parent channels handle accept-and-initialize; child channels run your handlers. ChannelInitializer's generic type must match the channel type in the bootstrap—a mismatch is a silent runtime failure.
- **ByteBuf shallow copies share fate with the source** (Early): slice() and duplicate() don't copy data or bump reference counts. If the source is released, all shallow copies become unusable. Call retain() on copies and release() twice—once for the source, once for the copy.
- **ReplayingDecoder trades simplicity for statefulness** (Early–Middle): It auto-rolls-back readerIndex on insufficient data, making decode logic read like sequential code. But the decoder holds state (checkpoints, phases), so it cannot be shared across channels—a constraint that catches many developers off guard.
- **LengthFieldBasedFrameDecoder solves framing, not protocols** (Early–Middle): Its five parameters (maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip) handle the common "length-prefixed" pattern, but you must understand lengthAdjustment for complex headers. Pair it with LengthFieldPrepender for symmetric encode/decode.
- **HTTP keep-alive is a connection-reuse strategy, not a magic switch** (Middle): HTTP/1.1 defaults to persistent connections, but you still need a pool to manage idle connections, avoid CLOSE_WAIT/TIME_WAIT buildup, and handle server-side timeouts. A global pooled HttpClient instance is the standard pattern.
## 【Reading Tips】
- **Skim the first 6%** if you already know NIO basics—the Buffer property explanations are thorough but standard. Focus instead on the file-transfer example to see NIO in a realistic scenario.
- **Deep-read the ByteBuf and codec chapters (roughly 19%–38%)**: These are the most reusable knowledge in the book. Pay special attention to the shallow-copy reference-counting discussion and the LengthFieldBasedFrameDecoder parameter walkthrough—both are common interview and production pain points.
- **The IM case study (roughly 38%–50%) is best read as a whole**: It ties together Protobuf, codecs, handlers, and heartbeats into one coherent system. Don't get lost in individual classes; trace the message flow from client send to server route to recipient.
- **The HTTP section (roughly 50%–63%) is skimmable if you've worked with HTTP before**: The key insight is the connection-pooling rationale and the HttpClient pattern. The header-by-header breakdown is reference material, not reading material.
- **Watch for the author's cross-references**: The book points to a companion volume on Spring Cloud/Nginx and an open-source WebSocket chat room project. These are optional but useful if you want to see the patterns applied at larger scale.
## 【Coverage Limits】
The excerpts do not cover Redis in any depth despite the title, nor do they include ZooKeeper's API-level details or distributed coordination recipes (leader election, distributed locks). The guide's coverage is strongest on NIO, Netty, and HTTP connection management.
##
Excerpt 1
sengFileNameAndLength(destFile, file, socketChannel); //发送文件内容 int length = sendContent(file, fileChannel, socketChannel, buffer); if (length == -1) { IOUtil...
View in text
Excerpt 2
候,如果容量不足,可以进行扩 容。扩容的最大限度由maxCapacity来设定,超过maxCapacity 就会报错。 ByteBuf的这三个重要属性的含义如图5-20所示。 图5-20 ByteBuf内部的三个重要属性的含义 5.7.4 ByteBuf的方法 ByteBuf的方法大致可以分为三组。 第一组:容量...
View in text
Excerpt 3
xHandler() { super(new Byte2IntegerDecoder(), new Integer2ByteEncoder()); } } 只需要继承CombinedChannelDuplexHandler,而不需要像 ByteToMessageCodec那样把编码逻辑和解码逻辑都挤在同一个类中,...
View in text
Excerpt 4
对性能和速度的要求是比较高的, 需要HTTP下层TCP传输层的连接通道具备可复用的能力,以提升响应效 率和高并发能力。 socket()、bind()、listen()来完成。开始监听之后,服务端就做好 接受外来连接的准备,如果监听到建立新连接的请求,就会开启一个 传输套接字,称之为被动打开(Passive Op...
View in text
Excerpt 5
仓 库的代码,其方法的名称为importCert,代码如下: package com.crazymakercircle.keystore; //省略import public class KeyStoreHelper { //省略成员属性 * 导入数字证书到信任仓库 { //关闭serverSocket监听套接字...
View in text
Excerpt 6
/listener/remoteNode"; private String subWorkerPath = "/test/listener/remoteNode/id-"; * NodeCache 节点缓存的监听 @Test public void testNodeCache() { //检查节点是否存在,没有则...
View in text
Excerpt 7
common.bean.User; import com.crazymakercircle.util.Logger; @CachePut(key = "T(String).valueOf(#user.uid)", condition = "#user.uid>1000") public User cacheUse...
View in text
Tags
AI categories
BackendProgramming Language
Text Preview (First 20 pages)
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Generating text preview…
Loading comments...
Reply to Comment
Edit Comment