1.Buffer
1.1 重要屬性
- capacity:buffer中包含元素的個數(shù)赋秀。其值一旦確認(rèn)后不可更改。
- limit:第一個不可被讀元素的索引值待榔。
- position:下一個要被讀或者寫元素的索引值逞壁。
三個屬性之間的關(guān)系:0 <= mark <= position <= limit <= capacity 。
1.2 重要方法
clear
用來讓一個buffer的屬性回到特定值锐锣,相當(dāng)于達(dá)到了清空buffer中元素的效果腌闯。
public final Buffer clear() {
position = 0;
limit = capacity;
mark = -1;
return this;
}
flip
在讀寫進行切換操作的時候使用。
public final Buffer flip() {
limit = position;
position = 0;
mark = -1;
return this;
}
rewind
用來對buffer進行重讀雕憔。
public final Buffer rewind() {
position = 0;
mark = -1;
return this;
}
2.ByteBuffer
ByteBuffer是Buffer的一個實現(xiàn)姿骏。
該類定義了6種byte buffers的操作方法:
- 用來讀取/寫入的絕對/相對方法
- 將緩沖區(qū)中的字節(jié)序列輸出到數(shù)組中
- 將數(shù)組或者其他的buffer中的字節(jié)序列輸出到另一個buffer中
- 與字符有關(guān)的操作
- 創(chuàng)建buffer的方法
- 壓縮、復(fù)制斤彼、劃分buffer
3.ByteBuf
ByteBuf的劃分
ByteBuf劃分
3.1 discardReadBytes方法
當(dāng)buffer中可寫空間不足時分瘦,可以調(diào)用該方法,通過將readerIndex設(shè)置為0琉苇,并將readable bytes區(qū)間的內(nèi)容移到buffer的開頭嘲玫,并將writeIndex設(shè)置為writeIndex-readerIndex,實現(xiàn)了清空已讀部分內(nèi)容的作用并扇。
@Override
public ByteBuf discardReadBytes() {
ensureAccessible();
if (readerIndex == 0) {
return this;
}
if (readerIndex != writerIndex) {
// 移動剩余未讀部分
setBytes(0, this, readerIndex, writerIndex - readerIndex);
// 重現(xiàn)調(diào)整Index值
writerIndex -= readerIndex;
adjustMarkers(readerIndex);
readerIndex = 0;
} else {
adjustMarkers(readerIndex);
writerIndex = readerIndex = 0;
}
return this;
}
3.2 calculateNewCapacity方法
該方法用來重新計算buffer的capacity的值去团。
@Override
public int calculateNewCapacity(int minNewCapacity, int maxCapacity) {
checkPositiveOrZero(minNewCapacity, "minNewCapacity");
//當(dāng)已分配的空間大于最大可分配空間時直接拋出異常
if (minNewCapacity > maxCapacity) {
throw new IllegalArgumentException(String.format(
"minNewCapacity: %d (expected: not greater than maxCapacity(%d)",
minNewCapacity, maxCapacity));
}
final int threshold = CALCULATE_THRESHOLD; // 1048576 * 4
if (minNewCapacity == threshold) {
return threshold;
}
// If over threshold, do not double but just increase by threshold.
if (minNewCapacity > threshold) {
int newCapacity = minNewCapacity / threshold * threshold;
if (newCapacity > maxCapacity - threshold) {
newCapacity = maxCapacity;
} else {
newCapacity += threshold;
}
return newCapacity;
}
// Not over threshold. Double up to 4 MiB, starting from 64.
int newCapacity = 64;
while (newCapacity < minNewCapacity) {
newCapacity <<= 1;
}
return Math.min(newCapacity, maxCapacity);
}
擴容分為兩種:
1.當(dāng)capacity<=threshold時,通過2的指數(shù)獲取到新的capacity;
2.當(dāng)capacity>threshold時土陪,capacity每次加上一個threshold的值昼汗,知道到達(dá)maxCapacity。
4.最主要區(qū)別鬼雀?
- ByteBuffer通過position和limit來控制讀取和寫入顷窒,每次切換讀寫時都需要調(diào)用flip方法,而ByteBuf通過writerIndex和readerIndex來簡化控制源哩。
- ByteBuffer中的capacity是一個固定值蹋肮,ByteBuf可以調(diào)用calculateNewCapacity方法來重新計算capacity值。
以上都是我個人看完doc文檔的想法璧疗,如有不足之處坯辩,請各位大佬指出。