增量capacity分配的ByteBuffer实现

前言


对于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(
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值