ByteBuffer

demo

public class ByteBufferTest {
    /**
     * 1. ByteBuffer 分为 2 种,HeapByteBuffer 和 DirectByteBuffer,即堆内和堆外
     * 2. ByteBuffer 的使用,就是 put 和 get,同时伴随着移动 postition
     * 3. 使用堆外内存的话,如何回收是个问题
     */
    public static void main(String[] args) {
        // capacity = 8, limit = 8, position = 0
        ByteBuffer buffer = ByteBuffer.allocate(8);
        ByteBuffer buffer2 = ByteBuffer.allocateDirect(8);
        // 字符转为字节,写入一个字节,写入数据后,postition 自动增加
        buffer.put((byte)'h');
        buffer.put((byte)'e');
        buffer.put((byte)'l');
        buffer.put((byte)'l');
        buffer.put((byte)'o');
        // 写入 5 个字节后,此时 position = 5

        // 创建一个新的 ByteBuffer 对象,底层的字节数组是同一个
        // postion, limit, cap 值有所不同
        // rocketMQ 使用 slice,先创建一个 MappedByteBuffer,不直接写入这个 ByteBuffer,不断地 slice,设置 postition,然后写入和读取
        ByteBuffer slice = buffer.slice();
        slice.position(0);
        slice.limit(3);

        // flip -> limit = position, position = 0
        // limit = 5, position = 0
        buffer.flip();

        // limit - position
        int len = buffer.remaining();
        byte[] dst = new byte[len];
        // 把 buffer 中的数据写入 dst 中
        // postition = 5
        buffer.get(dst);
        System.out.println(new String(dst));
        // 如需再次使用,需要调用 clear

        // 结论:HeapByteBuffer 只是对 byte[] 的封装
       // DirectByteBuffer 底层是用 Unsafe.allcoateMemory
  } 
}

 

原文地址:https://www.cnblogs.com/allenwas3/p/12248919.html