文章目录
前言
对于Java nio ByteBuffer,我们常常会拿来做缓冲数据的处理。如果我们就为了图方便,每次数据读写操作专门allocate一个比较大capacity的ByteBuffer,这样会造成不必要的JVM heap的浪费。但是如果我们转而变为多个小ByteBuffer的动态申请,又会加大ByteBuffer的管理协调 操作。那么有什么办法能结合上述二者的特点,做到既不浪费JVM heap空间的使用,又不用在业务上执行复杂的ByteBuffer逻辑。本文笔者介绍一个Ozone内部实现的增量ByteBuffer的实现。增量ByeBuffer在外部使用上和ByteBuffe原生r操作方法语义完全兼容,内部增量allocate capacity操作对调用方而言完全透明。
Ozone内部的增量ByteBuffer实现
这里简单介绍下Ozone的背景,Ozone作为对象存储系统,在存储对象文件的时候,会涉及到大量小数据对象的写入,以Chunk文件的形式进行物理存储。在读写chunk数据的过程中,Ozone使用了ByteBuffer做中间数据的存储。在初始实现中,Ozone内部初始的ByteBuffer allocate的capacity是比较大的,也不管用户写入的数据有多大。为此,后来社区实现了能够指定目标capacity,同时指定动态增量分配大小的ByteBuffer,名为IncrementalChunkBuffer。
以下为IncrementalChunkBuffer的实现代码,摘自Ozone项目:
/**
* Use a list of {@link ByteBuffer} to implement a single {@link ChunkBuffer}
* so that the buffer can be allocated incrementally.
*/
final class IncrementalChunkBuffer implements ChunkBuffer {
/**
* 全局Buffer的limit边界值
*/
private final int limit;
/** ByteBuffer的增量容量. */
private final int increment;
/** BytesBuffer下标数组边界值. */
private final int limitIndex;
/** 增量分配ByteBuffer数组 */
private final List<ByteBuffer> buffers;
/** Is this a duplicated buffer? (for debug only) */
private final boolean isDuplicated;
// 增量ByteBuffer总capacity(传入的limit值),每次动态增量increment值大小
IncrementalChunkBuffer(int limit, int increment, boolean isDuplicated) {
Preconditions.checkArgument(limit >= 0);
Preconditions.checkArgument(increment > 0);
// 初始化边界值,增量ByteBuffer值
this.limit = limit;
this.increment = increment;
// 计算ByteBuffer数组下标最大值
this.limitIndex = limit/increment;
// 初始空ByteBuffer数组
this.buffers = new ArrayList<>(limitIndex + (limit%increment == 0? 0: 1));
this.isDuplicated = isDuplicated;
}
/** @return the capacity for the buffer at the given index. */
private int getBufferCapacityAtIndex(int i) {
Preconditions.checkArgument(i >= 0);
Preconditions.checkArgument(i <= limitIndex);
return i < limitIndex? increment: limit%increment;
}
private void assertInt(int expected, int computed, String name, int i) {
ChunkBuffer.assertInt(expected, computed,
() -> this + ": Unexpected " + name + " at index " + i);
}
/** @return the i-th buffer if it exists; otherwise, return null. */
private ByteBuffer getAtIndex(int i) {
Preconditions.checkArgument(i >= 0);
Preconditions.checkArgument(i <= limitIndex);
final ByteBuffer ith = i < buffers.size() ? buffers.get(i) : null;
if (ith != null) {
// assert limit/capacity
if (!isDuplicated) {
assertInt(