zoukankan      html  css  js  c++  java
  • ByteBuffer 实现原理

    一,概述

      ByteBuffer 是Buffer类的重要实现类,nio中最常用的缓冲区,提供了一组功能用于操作byte数组

      缺点:无法自动扩容

      主要实现方式分为两种:

          1,直接操作内存的地址保存数据,实现类:DirectByteBuffer,

          2,内建字节数组保存数据,实现类:HeapByteBuffer

      类继承图

        

    二,实现类

      

    (1),DirectByteBuffer

    通过ByteBuffer 提供的函数获取 DirectByteBuffer的实例
    ByteBuffer sendBuf = ByteBuffer.allocate(10);//获取堆内存buff:使用byte数组保存数据
    DirectByteBuffer通过unsafe类实现堆外内存的操作
    1,构造器处理过程:
      cap:设置初始容量大小
    DirectByteBuffer(int cap) {                   // package-private
          //初始父类中的 mark,lim,pos,cap
            super(-1, 0, cap, cap);
         
            boolean pa = VM.isDirectMemoryPageAligned();//检查虚拟机中直接内存页是否对齐
         int ps = Bits.pageSize(); 

        long size = Math.max(1L, (long)cap + (pa ? ps : 0));       Bits.reserveMemory(size, cap);//预先向内存申请      long base = 0;      try { base = unsafe.allocateMemory(size);//分配内存、返回分配到的内存的首地址      } catch (OutOfMemoryError x) {         Bits.unreserveMemory(size, cap);         throw x;      }      unsafe.setMemory(base, size, (byte) 0);      if (pa && (base % ps != 0)) {        address = base + ps - (base & (ps - 1)); // 获取本buffer的首地址      } else {         address = base;      }                      cleaner = Cleaner.create(this, new Deallocator(base, size, cap));//保留地址,用于释放地址         att = null; }

     

    (2),HeapByteBuffer

    获取实例

    ByteBuffer sendBuf = ByteBuffer.allocate(10);//获取堆内存buff:使用byte数组保存数据
    基于堆的数据缓存区,数据处理比使用直接内存慢
    创建实例时,构造器new byte创建保存数据的Byte数组,cap设置的缓冲区大小





  • 相关阅读:
    taro clock组件
    创建taro项目
    ts声明各种变量类型
    ts的数组/元组/type/interface
    使用styled-components初始化css
    Oracle profile含义、修改、新增
    JDK bin指令
    Nginx 设置忽略favicon.ico文件的错误日志
    nginx: [error] CreateFile() "D: ginx-1.14.2/logs/nginx.pid" failed 解决办法
    Nginx Windows详细安装部署教程
  • 原文地址:https://www.cnblogs.com/dybe/p/11771751.html
Copyright © 2011-2022 走看看