https://dongzl.github.io/netty-handbook/#/_content/chapter03
测试代码
public class BasicBuffer {
public static void main(String[] args) {
LongBuffer longBuffer = LongBuffer.allocate(4);
System.out.println(longBuffer.mark() + "," + longBuffer.position()
+ "," + longBuffer.limit() + "," + longBuffer.capacity());
longBuffer.put(1234);
longBuffer.put(12345);
longBuffer.put(12346);
longBuffer.put(12347);
System.out.println("before flip: " + longBuffer.mark() + "," + longBuffer.position()
+ "," + longBuffer.limit() + "," + longBuffer.capacity());
longBuffer.flip();
System.out.println("after flip: " + longBuffer.mark() + "," + longBuffer.position()
+ "," + longBuffer.limit() + "," + longBuffer.capacity());
while(longBuffer.hasRemaining()) {
System.out.println(longBuffer.get());
System.out.println("after get: " + longBuffer.mark() + "," + longBuffer.position()
+ "," + longBuffer.limit() + "," + longBuffer.capacity());
}
}
}
解读
最开始 LongBuffer.allocate(4),可以看到初始
mark=-1,position=0,limit=4,capacity=4。
public abstract class LongBuffer
extends Buffer
implements Comparable<LongBuffer>
{
public static LongBuffer allocate(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException();
return new HeapLongBuffer(capacity, capacity);
}
}
class HeapLongBuffer
extends LongBuffer
{
HeapLongBuffer(int cap, int lim) { // package-private
super(-1, 0, lim, cap, new long[cap], 0);
/*
hb = new long[cap];
offset = 0;
*/
}
}
public abstract class LongBuffer
extends Buffer
implements Comparable<LongBuffer>
{
final long[] hb; // Non-null only for heap buffers
final int offset;
LongBuffer(int mark, int pos, int lim, int cap, // package-private
long[] hb, int offset)
{
super(mark, pos, lim, cap);
this.hb = hb;
this.offset = offset;
}
}
而put数据过程,就是position 索引不断增加过程;
调用的是HeapLongBuffer#put()
class HeapLongBuffer
extends LongBuffer
{
public LongBuffer put(long x) {
hb[ix(nextPutIndex())] = x;
return this;
}
protected int ix(int i) {
return i + offset;
}
}
flip()则是将position赋值给limit,position置为0
public final Buffer flip() {
limit = position;
position = 0;
mark = -1;
return this;
}
get()则调用HeapLongBuffer#get(),取hb数组中position值
class HeapLongBuffer
extends LongBuffer
{
public long get() {
return hb[ix(nextGetIndex())];
}
final int nextGetIndex() { // package-private
if (position >= limit)
throw new BufferUnderflowException();
return position++;
}
}