美文网首页
JDK-HeapByteBuffer源码阅读

JDK-HeapByteBuffer源码阅读

作者: 麻瓜镇 | 来源:发表于2016-10-06 11:20 被阅读0次

本文尝试较为仔细的阅读HeapByteBuffer类的代码。
首先,我们知道HeapByteBuffer继承自ByteBuffer,而ByteBuffer又是Buffer的子类。所以我们先来看看什么是Buffer
<blockquote>
A buffer is a linear, finite sequence of elements of a specific primitive type.
Aside from its content, the essential properties of a buffer are its capacity, limit, and position:
</blockquote>
Buffer是某种Java类型的对象的一个有限的线性序列。除了序列内容之外,主要的属性还有capacity,limit以及position。第一句话很好懂,就是说其实Buffer本质上是一个数组,第二句话里的三个属性,JDK解释如下:
<blockquote>
<p>A buffer's capacity is the number of elements it contains. The capacity of a buffer is never negative and never changes.
A buffer's limit is the index of the first element that should not be read or written. A buffer's limit is never negative and is never greater than its capacity.
limit 是buffer的界限,这个位置不可读也不可写。limit不能比capacity大
A buffer's position is the index of the next element to be read or written. A buffer's position is never negative and is never greater than its limit. </p>
<p>capacity 是buffer的最大容量,初始化时指定,不可更改。
limit 是buffer的界限,这个位置不可读也不可写。limit不能比capacity大
position是读或写的下一个元素的index。position不能比limit大</p>
</blockquote>

本文主要探讨HeapByteBuffer,顾名思义,这个Buffer的对象是Byte,而这些Byte是在堆上的。所以,除了上面的三个属性之外,HeapByteBuffer还有继承自ByteBuffer的两个成员:

final byte[] hb;
final int offset;

hb 即 heapbyte 的意思,而 offset 是指从 byte 数组的这个位置开始作为 buffer 的空间。

Buffer的用途是传递数据,下面我们来看一下HeapByteBuffer用于传递数据的方法。
Buffer可以双向传递数据,从Buffer读数据是get,写数据是put,读写操作有两类,一类是从相对位置(也就是当前位置)读写,另一类是从绝对位置读写,让我们从代码来看一下:
下面一段代码是读写当前位置byte的代码,也就是从相对位置读/写一个byte的代码,在操作前判断越界是否越界,而且将position指向下一个位置。

//ix 通过计算返回 buffer 的下标 i 所对应的 byte array 的下标
protected int ix(int i) {
    return i + offset;
}

//nextGetIndex 在判断是否越界之后,返回当前position的下标,并累加1指向下一个位置
final int nextGetIndex() {                          // package-private
    if (position >= limit)
        throw new BufferUnderflowException();
    return position++;
}

//返回当前位置的byte,然后position指向了下一个位置
public byte get() {
    return hb[ix(nextGetIndex())];
}

public ByteBuffer put(byte x) {
    hb[ix(nextPutIndex())] = x;
    return this;
}

下面我们看到的是读写指定位置的一个byte,操作前当然也要判断指定的位置是否越界

final int checkIndex(int i) {                       // package-private
    if ((i < 0) || (i >= limit))
        throw new IndexOutOfBoundsException();
    return i;
}

public byte get(int i) {
    return hb[ix(checkIndex(i))];
}

public ByteBuffer put(int i, byte x) {
    hb[ix(checkIndex(i))] = x;
    return this;
}

上面两组读写接口都是读写单个byte的,HeapByteBuffer还支持读写一组byte的操作

static void checkBounds(int off, int len, int size) { // package-private
    //下面四个数据任何一个小于0,都越界
    if ((off | len | (off + len) | (size - (off + len))) < 0)
        throw new IndexOutOfBoundsException();
}

//修改buffer的position
public final Buffer position(int newPosition) {
    if ((newPosition > limit) || (newPosition < 0))
        throw new IllegalArgumentException();
    position = newPosition;
    if (mark > position) mark = -1;
    return this;
}

public ByteBuffer get(byte[] dst, int offset, int length) {
    checkBounds(offset, length, dst.length);
    if (length > remaining())
        throw new BufferUnderflowException();
    /**
     * 从buffer的hb数组,copy到参数dst数组中
     * 从hb的ix(position)开始,dst数组的起始index为offset
     * copy的数据长度为length
     */
    System.arraycopy(hb, ix(position()), dst, offset, length);
    position(position() + length);
    return this;
}

public ByteBuffer put(byte[] src, int offset, int length) {
    checkBounds(offset, length, src.length);
    if (length > remaining())
        throw new BufferOverflowException();
    System.arraycopy(src, offset, hb, ix(position()), length);
    position(position() + length);
    return this;
}

ByteBuffer的数据结构可以看出,只有position一个指针随着buffer内数据的变化而移动,那么我们在读写数据的时候,如何保证能够正确的操作ByteBuffer中的byte数组呢?
实际上我们可以认为Buffer有两个操作模式:Write Mode和Read Mode。
最开始一个空的Buffer处于Write Mode,然后通过一些方式写入数据之后,position指向了写入的数据后面的第一个位置。此时,通过flip()方法切换至Read Mode,这时,limit被设置到position的位置,而position回到Buffer的开头位置。
如下图所示:

Paste_Image.png
我们来看一下flip()的代码:
public final Buffer flip() {
    limit = position;
    position = 0;
    mark = -1;
    return this;
}

可以很清晰的看出,通过操作position和limit的位置,来实现从写模式到读模式的切换。那么如何在读操作进行完之后,切换回写操作呢?看下面一段代码:

public final Buffer clear() {
    position = 0;
    limit = capacity;
    mark = -1;
    return this;
}

position置回开头,limit设置为最大容量,并不用清空byte数组的内容,直接让新的数据覆盖即可。

相关文章

网友评论

      本文标题:JDK-HeapByteBuffer源码阅读

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