Unpooled 类结构分析
Unpooled 是 Netty Buffer 包中的工厂类,提供了创建各种类型 ByteBuf 的静态方法。它是一个不可实例化的工具类,专门用于创建非池化的 ByteBuf 实例。
public final class Unpooled {
private static final ByteBufAllocator ALLOC = UnpooledByteBufAllocator.DEFAULT;
private Unpooled() { /* 不可实例化 */ }
}
提供的核心能力
1. 基础 Buffer 创建
// 堆内存 Buffer
public static ByteBuf buffer(); // 默认容量堆 buffer
public static ByteBuf buffer(int initialCapacity); // 指定初始容量
public static ByteBuf buffer(int initial, int max); // 指定初始和最大容量
// 直接内存 Buffer
public static ByteBuf directBuffer(); // 默认容量直接 buffer
public static ByteBuf directBuffer(int initialCapacity); // 指定初始容量
2. 包装(Wrapping)能力
零拷贝包装现有数据:
// 包装字节数组
public static ByteBuf wrappedBuffer(byte[] array);
public static ByteBuf wrappedBuffer(byte[] array, int offset, int length);
// 包装 NIO ByteBuffer
public static ByteBuf wrappedBuffer(ByteBuffer buffer);
// 包装内存地址
public static ByteBuf wrappedBuffer(long memoryAddress, int size, boolean doFree);
// 组合包装多个数据源
public static ByteBuf wrappedBuffer(byte[]... arrays);
public static ByteBuf wrappedBuffer(ByteBuf... buffers);
public static ByteBuf wrappedBuffer(ByteBuffer... buffers);
3. 复制(Copying)能力
深拷贝数据创建新 Buffer:
// 复制字节数组
public static ByteBuf copiedBuffer(byte[] array);
public static ByteBuf copiedBuffer(byte[] array, int offset, int length);
// 复制 NIO ByteBuffer
public static ByteBuf copiedBuffer(ByteBuffer buffer);
// 复制 ByteBuf
public static ByteBuf copiedBuffer(ByteBuf buffer);
// 合并复制多个数据源
public static ByteBuf copiedBuffer(byte[]... arrays);
public static ByteBuf copiedBuffer(ByteBuf... buffers);
// 从字符串创建
public static ByteBuf copiedBuffer(CharSequence string, Charset charset);
4. 组合 Buffer 创建
// 创建组合 Buffer
public static CompositeByteBuf compositeBuffer();
public static CompositeByteBuf compositeBuffer(int maxNumComponents);
5. 基本类型数据 Buffer
// 创建包含基本类型数据的 Buffer
public static ByteBuf copyInt(int value);
public static ByteBuf copyLong(long value);
public static ByteBuf copyShort(int value);
public static ByteBuf copyFloat(float value);
public static ByteBuf copyDouble(double value);
public static ByteBuf copyBoolean(boolean value);
6. 特殊 Buffer 类型
// 空 Buffer
public static final ByteBuf EMPTY_BUFFER;
// 只读 Buffer
public static ByteBuf unmodifiableBuffer(ByteBuf buffer);
public static ByteBuf wrappedUnmodifiableBuffer(ByteBuf... buffers);
// 不可释放 Buffer
public static ByteBuf unreleasableBuffer(ByteBuf buf);
关键实现分析
1. 智能 ByteBuffer 包装策略
根据 ByteBuffer 的特性选择最优的包装实现
public static ByteBuf wrappedBuffer(ByteBuffer buffer) {
if (!buffer.hasRemaining()) {
return EMPTY_BUFFER; // 空 buffer 优化
}
if (!buffer.isDirect() && buffer.hasArray()) {
// 堆内存 ByteBuffer 直接包装底层数组
return wrappedBuffer(
buffer.array(),
buffer.arrayOffset() + buffer.position(),
buffer.remaining()).order(buffer.order());
} else if (PlatformDependent.hasUnsafe()) {
if (buffer.isReadOnly()) {
// 只读直接内存 buffer
return buffer.isDirect() ?
new ReadOnlyUnsafeDirectByteBuf(ALLOC, buffer) :
new ReadOnlyByteBufferBuf(ALLOC, buffer);
} else {
// 可写直接内存 buffer
return new UnpooledUnsafeDirectByteBuf(ALLOC, buffer, buffer.remaining());
}
} else {
// 无 Unsafe 支持的 fallback
return buffer.isReadOnly() ?
new ReadOnlyByteBufferBuf(ALLOC, buffer) :
new UnpooledDirectByteBuf(ALLOC, buffer, buffer.remaining());
}
}
关键技术点:
- 条件分支优化 - 根据 buffer 特性选择最优实现
- Unsafe 检测 - 利用 Unsafe API 提升性能
- 内存类型识别 - 区分堆内存和直接内存处理
2. 组合 Buffer 的智能创建
难点:高效处理多个数据源的组合,避免不必要的复制
static <T> ByteBuf wrappedBuffer(int maxNumComponents, ByteWrapper<T> wrapper, T[] array) {
switch (array.length) {
case 0:
break;
case 1:
if (!wrapper.isEmpty(array[0])) {
return wrapper.wrap(array[0]); // 单个非空直接包装
}
break;
default:
// 跳过空数据,找到第一个非空数据
for (int i = 0, len = array.length; i < len; i++) {
T bytes = array[i];
if (bytes == null) {
return EMPTY_BUFFER;
}
if (!wrapper.isEmpty(bytes)) {
// 从第一个非空数据开始创建组合 buffer
return new CompositeByteBuf(ALLOC, false, maxNumComponents, wrapper, array, i);
}
}
}
return EMPTY_BUFFER;
}
关键技术点:
- 泛型包装器模式 - 统一处理不同类型数据源
- 惰性创建策略 - 只在必要时创建 CompositeByteBuf
- 空数据跳过 - 避免包含无效数据段
3. 字符编码优化处理
难点:针对常用字符集进行特殊优化
public static ByteBuf copiedBuffer(CharSequence string, Charset charset) {
if (CharsetUtil.UTF_8.equals(charset)) {
return copiedBufferUtf8(string); // UTF-8 特殊优化
}
if (CharsetUtil.US_ASCII.equals(charset)) {
return copiedBufferAscii(string); // ASCII 特殊优化
}
// 通用处理
return copiedBuffer(CharBuffer.wrap(string), charset);
}
private static ByteBuf copiedBufferUtf8(CharSequence string) {
ByteBuf buffer = ALLOC.heapBuffer(ByteBufUtil.utf8Bytes(string)); // 预计算容量
try {
ByteBufUtil.writeUtf8(buffer, string); // 优化的 UTF-8 写入
return buffer;
} finally {
// 异常安全的资源管理
}
}
关键技术点:
- 字符集识别优化 - 为常用字符集提供快速路径
- 容量预计算 - 避免 buffer 扩容开销
- 异常安全 - 确保资源正确释放
4. 内存安全与边界检查
难点:处理大量数据合并时的整数溢出风险
public static ByteBuf copiedBuffer(byte[]... arrays) {
int length = 0;
for (byte[] a: arrays) {
if (Integer.MAX_VALUE - length < a.length) {
throw new IllegalArgumentException(
"The total length of the specified arrays is too big.");
}
length += a.length; // 安全的长度累加
}
}
设计优势
- 统一接口 - 提供一致的 Buffer 创建 API
- 零拷贝优化 - wrappedBuffer 系列方法避免数据复制
- 性能优化 - 针对不同场景选择最优实现
- 内存安全 - 完善的边界检查和异常处理
- 易用性 - 支持静态导入,简化使用
Unpooled 作为 Netty 的 Buffer 工厂,通过智能的实现选择和优化策略,为用户提供了高性能、易用的 ByteBuf 创建能力。
Unpooled 类依赖关系分析
核心依赖架构
1. 分配器层(Allocator Layer)
Unpooled
└── UnpooledByteBufAllocator.DEFAULT (ALLOC)
└── AbstractByteBufAllocator.DEFAULT_MAX_COMPONENTS
作用:提供统一的内存分配接口,所有 buffer 创建都通过此分配器完成。
2. 具体实现类层(Implementation Layer)
堆内存实现
Unpooled
├── UnpooledHeapByteBuf (包装字节数组)
└── EmptyByteBuf (空buffer实现)
直接内存实现
Unpooled
├── UnpooledDirectByteBuf (基础直接内存)
├── UnpooledUnsafeDirectByteBuf (Unsafe优化版本)
├── ReadOnlyUnsafeDirectByteBuf (只读Unsafe版本)
├── ReadOnlyByteBufferBuf (只读NIO包装)
└── WrappedUnpooledUnsafeDirectByteBuf (内存地址包装)
组合实现
Unpooled
├── CompositeByteBuf (可变组合buffer)
└── FixedCompositeByteBuf (固定组合buffer)
特殊包装实现
Unpooled
├── UnreleasableByteBuf (不可释放包装)
└── ReadOnlyByteBuf (只读包装)
工具支持层(Utility Layer)
字节序支持
ByteOrder.BIG_ENDIAN
ByteOrder.LITTLE_ENDIAN
平台检测
PlatformDependent.hasUnsafe() // Unsafe可用性检测
PlatformDependent.allocateUninitializedArray() // 优化数组分配
字符集处理
CharsetUtil.UTF_8
CharsetUtil.US_ASCII
ByteBufUtil.utf8Bytes()
ByteBufUtil.writeUtf8()
ByteBufUtil.writeAscii()
ByteBufUtil.encodeString0()
参数验证
ObjectUtil.checkNotNull() // 空值检查
包装器模式层(Wrapper Pattern Layer)
CompositeByteBuf.ByteWrapper<T> // 泛型包装接口
├── BYTE_ARRAY_WRAPPER // 字节数组包装器
└── BYTE_BUFFER_WRAPPER // ByteBuffer包装器
设计模式应用
1. 工厂模式
- Unpooled 作为静态工厂类
- 根据不同参数创建不同类型的 ByteBuf
2. 策略模式
- 根据平台能力选择不同实现
- Unsafe 可用时选择 UnsafeDirectByteBuf
- 不可用时回退到标准实现
3. 包装器模式
ByteWrapper<T>统一处理不同数据源- 泛型设计支持扩展新的数据类型
4. 模板方法模式
wrappedBuffer(int maxNumComponents, ByteWrapper<T> wrapper, T[] array)- 提供统一的包装逻辑模板

1119

被折叠的 条评论
为什么被折叠?



