程序员

三.Buffer

2017-09-26  本文已影响0人  蜗牛1991

一.Buffer

image.png
/*参数:以写为例*/
//存储当前位置
 private int mark = -1;
//写入数据当前的位置
 private int position = 0;
//最多能往Buffer里写多少数据,写模式下,limit等于Buffer的capacity
 private int limit;
//作为一个内存块,Buffer有一个固定的大小值,通过读数据或者清除数据清除buffer。
 private int capacity;
//仅用于直接缓存区,代表内存映射的地址
 long address;
image.png
 public final Buffer flip() {
        limit = position;
        position = 0;
        mark = -1;
        return this;
    }

二.ByteBuffer

// 不为空且只供非直接缓存区使用
final byte[] hb;      
// 数组偏移量
final int offset;
ByteBuffer(int mark, int pos, int lim, int cap,   // package-private
                 byte[] hb, int offset)
    {
      //继承Buffer的构造器
        super(mark, pos, lim, cap);
        this.hb = hb;
        this.offset = offset;
    }            
 public static ByteBuffer allocate(int capacity) {
               ......
        return new HeapByteBuffer(capacity, capacity);
    }
public ByteBuffer put(int i, byte x) {
        hb[ i + offset] = x;
        return this;
    }
  
  public ByteBuffer put(byte[] src, int offset, int length) {

        checkBounds(offset, length, src.length);
        if (length > remaining())
            throw new BufferOverflowException();
      //src复制到hb中
        System.arraycopy(src, offset, hb, ix(position()), length);
        position(position() + length);
        return this;
    }
public byte get() {
        return hb[position++];
    }
 public static ByteBuffer allocateDirect(int capacity) {
        return new DirectByteBuffer(capacity);
    }
  DirectByteBuffer(int 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)) {
            // Round up to page boundary
            address = base + ps - (base & (ps - 1));
        } else {
          //保存基地址(虚拟地址)
            address = base;
        }
        cleaner = Cleaner.create(this, new Deallocator(base, size, cap));
        att = null;
    }

总结

参考:
从0到1起步-跟我进入堆外内存的奇妙世界
浅析Java Nio 之缓冲区

上一篇 下一篇

猜你喜欢

热点阅读