Java ByteBuffer

1. ByteBuffer 6大类操作

num method desc
1 get,put(byte)
2 get(byte[])
3 put(byte)
4 getChar(),putChar(char)
5 view buffer allow a byte buffer to be viewed as a buffer containing values of some other primitive type
6 compact,duplicate,slice

Byte Buffer的创建方式:

  1. allocation
  2. wrap(byte[]): 将byte array 转成一个buffer

2. Direct vs non-direct buffers

  1. byte buffer是不是只有direct/non-direct 2种?

    是的

  2. 为什么会有direct形式的buffer?

    JVM will make a best effort to perform native I/O operations directly upon it. That is, it will attempt to avoid copying the buffer's content to (or from) an intermediate buffer before (or after) each invocation of one of the underlying operating system's native I/O operations

  3. java中如何创建一个direct buffer?

    ByteBuffer.allocateDirect(int capacity),具体是一个DirectByteBuffer

  4. direct buffer的缺点?

    分配和回收的时候开销大于not-direct的buffer,这块内存是独立于gc可回收的堆,需要格外注意

  5. direct buffer的应用场景?

    It is therefore recommended that direct buffers be allocated primarily for large, long-lived buffers that are subject to the underlying system's native I/O operations. In general it is best to allocate direct buffers only when they yield a measureable gain in program performance

  6. direct buffer另外的创建方式?

    java.nio.channels.FileChannel#map将一个文件的区域直接映射到内存,具体是一个MappedByteBuffer

  7. 怎么判断一个buffer是不是direct的?

    isDirect(),在ByteBuffer的3中实现里面写死了(DirectByteBuffer,DirectByteBufferR,HeapByteBuffer)

3. 访问(读/写)二进制数据

除了boolean类型以外,都可以根据buffer当前的ByteOrder将bytes序列转换成/转换自 基本类型

1. 访问 heterogeneous binary data

  1. 绝对访问: getFloat(),putFloat(float f)
  2. 相对访问: getFloat(int index),putFloat(int index, float f),其中index表示的单位是以byte为单位,而不是以读的类型为单位(即indexindex+1之间差了1个byte/8bit,而不是8bit/16bit/32bit/64bit这种因类型而变的bit)

2. 访问 homogeneous binary data

因为此时buffer(byte array)中的数据都是同一个类型,所以可以在其上做一层抽象,底层依然是一个byte buffer,所以称其为view buffer,使用asFloatBuffer这样的方法创建

view buffer的访问方式比上面提到的访问方式有以下3点好处:

  1. index是以类型的单位的
  2. 相对访问形式的批量get,put方法,将buffer中连续的值转化为array,或者反之
  3. view buffer拥有其下buffer的direct/non-direct属性和byte order

你可能感兴趣的:(Java ByteBuffer)