ByteBuffer详解

作者: TTTTTriM | 来源:发表于2018-12-14 10:47 被阅读11次

Bytebuffer
官方解释A byte buffer,一个字节缓冲区。

ByteBuffer的扩展

HeapByteBuffer 和 DirectByteBuffer


Bytebuffer UML图
- 描述 优点
HeapByteBuffer 在jvm堆上面的一个buffer,底层的本质是一个数组 由于内容维护在jvm里,所以把内容写进buffer里速度会快些;并且,可以更容易回收
DirectByteBuffer 底层的数据其实是维护在操作系统的内存中,而不是jvm里,DirectByteBuffer里维护了一个引用address指向了数据,从而操作数据 跟外设(IO设备)打交道时会快很多,因为外设读取jvm堆里的数据时,不是直接读取的,而是把jvm里的数据读到一个内存块里,再在这个块里读取的,如果使用DirectByteBuffer,则可以省去这一步,实现zero copy

ByteBuffer的属性及方法

ByteBuffer的属性
     byte[] buff  //buff即内部用于缓存的数组。
     position //当前读取的位置。
     mark //为某一读过的位置做标记,便于某些时候回退到该位置。
     capacity //初始化时候的容量。
     limit //当写数据到buffer中时,limit一般和capacity相等,当读数据时,limit代表buffer中有效数据的长度。

这些属性总是满足以下条件:
  0 <= mark <= position <= limit <= capacity

ByteBuffer的常规方法
     ByteBuffer allocate(int capacity) //创建一个指定capacity的ByteBuffer。
     ByteBuffer allocateDirect(int capacity) //创建一个direct的ByteBuffer,这样的ByteBuffer在参与IO操作时性能会更好
     ByteBuffer wrap(byte [] array)
     ByteBuffer wrap(byte [] array, int offset, int length) //把一个byte数组或byte数组的一部分包装成ByteBuffer。
     //get put方法不多说
     byte get(int index)
     ByteBuffer put(byte b)
     int getInt()             //从ByteBuffer中读出一个int值。
     ByteBuffer putInt(int value)  // 写入一个int值到ByteBuffer中。
ByteBuffer的特殊方法
     Buffer clear()    把position设为0,把limit设为capacity,一般在把数据写入Buffer前调用。
     Buffer flip()    把limit设为当前position,把position设为0,一般在从Buffer读出数据前调用。
     Buffer rewind()  把position设为0,limit不变,一般在把数据重写入Buffer前调用。
     compact()       将 position 与 limit之间的数据复制到buffer的开始位置,复制后 position = limit -position,limit = capacity, 但如         果position 与limit 之间没有数据的话发,就不会进行复制。
     mark() & reset()     通过调用Buffer.mark()方法,可以标记Buffer中的一个特定position。之后可以通过调用Buffer.reset()方法恢复到这个position。
图解ByteBuffer方法改变属性

put
写模式下,往buffer里写一个字节,并把postion移动一位。写模式下,一般limit与capacity相等。
flip
写完数据,需要开始读的时候,将postion复位到0,并将limit设为当前postion。
get
从buffer里读一个字节,并把postion移动一位。上限是limit,即写入数据的最后位置。
clear
将position置为0,并不清除buffer内容。
mark & reset
mark相关的方法主要是mark()(标记)和reset()(回到标记).

process

相关文章

  • ByteBuffer详解

    Bytebuffer官方解释A byte buffer,一个字节缓冲区。 ByteBuffer的扩展 HeapBy...

  • Buffer/ByteBuffer/ByteBuf详解

    ByteBuffer ByteBuffer是一个抽象类,NIO编程中经常会使用,Netty常用的ByteBuf实际...

  • java nio

    ByteBuffer 写文件 ByteBuffer读中文文件 ByteBuffer读取普通文件

  • 11.15

    Java 中怎么创建 ByteBuffer?1.1 使用allocate()静态方法ByteBuffer buff...

  • Netty内存分配原理

    1 java NIO的ByteBuffer Bytebuffer分为两种:HeapByteBuffer(堆内内存)...

  • ByteBuffer

    缓冲区(Buffer)缓冲区(Buffer)就是在内存中预留指定大小的存储空间用来对输入/输出(I/O)的数据作临...

  • ByteBuffer

    测试代码

  • Netty(二) ByteBuf

    Netty ByteBuf 是NIO中ByteBuffer的封装,相比JDK ByteBuffer更加易用; 为读...

  • NIO DirectByteBuffer 内存泄露的测试

    写NIO程序经常使用ByteBuffer来读取或者写入数据,那么使用ByteBuffer.allocate(...

  • 关于java的ByteBuffer与Netty ByteBuf的

    JDK的ByteBuffer的缺点:1.final byte hb;这是JDKde ByteBuffer对象中用于...

网友评论

    本文标题:ByteBuffer详解

    本文链接:https://www.haomeiwen.com/subject/tnmbhqtx.html