PoolArena
在PooledByteBufAllocate初始化最后一步,就是初始化PoolArena。PoolArena是對內存申請和釋放的一個抽象。在類層次上,PoolArena有2個子類DirectArena和HeapArena,并且將內存處理的工作都統一抽象到了PoolArena中。PoolArena主要管理的對象是tinySubpagePools、smallSubpagePools和PoolChunkList,前兩者在PoolSubpage一節已有提及,而PoolChunkList則是一組鏈表對象,并且會根據PoolChunk內存使用率的變化將其中的元素進行轉移。
PoolArena成員介紹
通過PoolArena的構造函數看一下常用成員變量,這里忽略了metric相關的變量。
protected PoolArena(PooledByteBufAllocator parent, int pageSize,
int maxOrder, int pageShifts, int chunkSize, int cacheAlignment) {
this.parent = parent;
this.pageSize = pageSize;
this.maxOrder = maxOrder;
this.pageShifts = pageShifts;
this.chunkSize = chunkSize;
directMemoryCacheAlignment = cacheAlignment;
directMemoryCacheAlignmentMask = cacheAlignment - 1;
subpageOverflowMask = ~(pageSize - 1);
tinySubpagePools = newSubpagePoolArray(numTinySubpagePools);
for (int i = 0; i < tinySubpagePools.length; i ++) {
tinySubpagePools[i] = newSubpagePoolHead(pageSize);
}
numSmallSubpagePools = pageShifts - 9;
smallSubpagePools = newSubpagePoolArray(numSmallSubpagePools);
for (int i = 0; i < smallSubpagePools.length; i ++) {
smallSubpagePools[i] = newSubpagePoolHead(pageSize);
}
q100 = new PoolChunkList<T>(this, null, 100, Integer.MAX_VALUE, chunkSize);
q075 = new PoolChunkList<T>(this, q100, 75, 100, chunkSize);
q050 = new PoolChunkList<T>(this, q075, 50, 100, chunkSize);
q025 = new PoolChunkList<T>(this, q050, 25, 75, chunkSize);
q000 = new PoolChunkList<T>(this, q025, 1, 50, chunkSize);
qInit = new PoolChunkList<T>(this, q000, Integer.MIN_VALUE, 25, chunkSize);
q100.prevList(q075);
q075.prevList(q050);
q050.prevList(q025);
q025.prevList(q000);
q000.prevList(null);
qInit.prevList(qInit);
構造函數前半段是一些熟悉的屬性——pageSize、maxOrder等,忽略掉這些屬性設置外,PoolArena主要的成員變量就是tinySubpagePools和smallSubpagePools,這2個在PoolSubpage一小節已經講述過,這里看一下PoolChunkList。
PoolChunkList
為了理解PoolChunkList,我們先看一下它的構造函數。
PoolChunkList實例化
PoolChunkList(PoolArena<T> arena, PoolChunkList<T> nextList, int minUsage, int maxUsage, int chunkSize) {
this.arena = arena;
this.nextList = nextList;
this.minUsage = minUsage;
this.maxUsage = maxUsage;
maxCapacity = calculateMaxCapacity(minUsage, chunkSize);
}
private static int calculateMaxCapacity(int minUsage, int chunkSize) {
minUsage = Math.max(1, minUsage);
if (minUsage == 100) {
return 0;
}
return (int) (chunkSize * (100L - minUsage) / 100L);
}
在構造函數中定義了PoolChunkList中元素的內存最小、最大使用率,并且根據最小占用率計算出最大內存容量。此外由nextList還可以看出來,PoolChunkList除了自身是一條PoolChunk的鏈表外,不同的PoolChunkList還會形成一個鏈表。除了上述幾個成員變量外,PoolChunkList還有head和prevList,前者指向PoolChunk的最新加入的節點,后者是PoolChunkList的前繼節點。
PoolChunkList添加PoolChunk
接著看一下PoolChunkList添加PoolChunk的add方法。add方法在3種情況被調用:
- 新創建的Chunk,由一個特殊的PoolChunkList——qInit調用,加入鏈表中。
- 在chunk內存使用率變化時,需要調整其所在鏈表時調用
- 調整鏈表時,發現當前PoolChunkList不滿足內存使用率,遞歸調用。
void add(PoolChunk<T> chunk) {
if (chunk.usage() >= maxUsage) {
nextList.add(chunk);
return;
}
add0(chunk);
}
void add0(PoolChunk<T> chunk) {
chunk.parent = this;
if (head == null) {
head = chunk;
chunk.prev = null;
chunk.next = null;
} else {
chunk.prev = null;
chunk.next = head;
head.prev = chunk;
head = chunk;
}
}
add方法首先計算傳入的chunk的使用率,如果使用率超過了當前PoolChunkList的最大使用率,則遞歸調用add方法,直到尋找到合適的PoolChunkList后,調用add0。add0就是流程化的雙向鏈表頭插法添加操作。
PoolChunkList移動PoolChunk
與add相反的是move操作,在free內存或者調整內存使用率時,move0方法被調用,它會根據chunk的使用率將其從高使用率的PoolChunkList移動到低使用率的PoolChunkList中。
private boolean move0(PoolChunk<T> chunk) {
if (prevList == null) {
assert chunk.usage() == 0;
return false;
}
return prevList.move(chunk);
}
private boolean move(PoolChunk<T> chunk) {
if (chunk.usage() < minUsage) {
return move0(chunk);
}
add0(chunk);
return true;
}
move0這里首先進行判斷,如果當前節點為0,意味著chunk是從q000鏈表移除,而q000的最小使用率為1%,所以這里做了一個斷言chunk使用率為0。之后調用prevList的move方法。
move方法也是先判斷使用率是否小于調用者最小使用率,若小于則再次調用move0方法,否則將chunk添加到調用該方法的PoolChunkList中。
PoolChunkList申請內存
boolean allocate(PooledByteBuf<T> buf, int reqCapacity, int normCapacity) {
if (normCapacity > maxCapacity) {
return false;
}
for (PoolChunk<T> cur = head; cur != null; cur = cur.next) {
if (cur.allocate(buf, reqCapacity, normCapacity)) {
if (cur.usage() >= maxUsage) {
remove(cur);
nextList.add(cur);
}
return true;
}
}
return false;
}
首先注意到有2個capacity的入參,一個是reqCapacity,表示外部請求申請的內存大小,一個是normCapacity,表示經過規整化為2的冪次方的內存大小,也是實際申請的內存大小,所以在與PoolChunkList的maxCapacity判斷時用的maxCapacity。
滿足內存大小申請條件后,用當前PoolChunkList內部的PoolChunk鏈表一個個嘗試申請。如果在某個PoolChunk申請內存后,發現其內存使用率超過了當前PoolChunkList的最大使用率,則將其轉移到下一個PoolChunkList中去。
PoolChunkList初始化
回到PoolArena中,這里初始化了6個PoolChunkList,組成了一個q000 <-> q025 <-> q050 <-> q075 <-> q100的雙向鏈表。qInit比較特殊,他的后繼節點是q000,但前繼節點是自身。從名字上也可以看出,qInit負責創建PoolChunk,且在PoolChunk使用率超過qInit的maxUsage(25%)后,將其轉移到q000鏈表去。因為q000最小使用率就是1%,再小就沒必要留著PoolChunk了,因此q000的前繼節點為null。
PoolArena申請內存
外界通過調用allocate(PoolThreadCache cache, int reqCapacity, int maxCapacity)方法來申請內存。
PooledByteBuf<T> allocate(PoolThreadCache cache, int reqCapacity, int maxCapacity) {
PooledByteBuf<T> buf = newByteBuf(maxCapacity);
allocate(cache, buf, reqCapacity);
return buf;
}
這個方法首先調用了一個抽象方法newByteBuf(int maxCapacity)獲取到PooledByteBuf,然后將申請的內存通過的allocate方法放入這個ByteBuf中。
private void allocate(PoolThreadCache cache, PooledByteBuf<T> buf, final int reqCapacity) {
final int normCapacity = normalizeCapacity(reqCapacity);
if (isTinyOrSmall(normCapacity)) {
int tableIdx;
PoolSubpage<T>[] table;
boolean tiny = isTiny(normCapacity);
if (tiny) {
if (cache.allocateTiny(this, buf, reqCapacity, normCapacity)) {
return;
}
tableIdx = tinyIdx(normCapacity);
table = tinySubpagePools;
} else {
if (cache.allocateSmall(this, buf, reqCapacity, normCapacity)) {
return;
}
tableIdx = smallIdx(normCapacity);
table = smallSubpagePools;
}
final PoolSubpage<T> head = table[tableIdx];
synchronized (head) {
final PoolSubpage<T> s = head.next;
if (s != head) {
assert s.doNotDestroy && s.elemSize == normCapacity;
long handle = s.allocate();
assert handle >= 0;
s.chunk.initBufWithSubpage(buf, null, handle, reqCapacity);
incTinySmallAllocation(tiny);
return;
}
}
synchronized (this) {
allocateNormal(buf, reqCapacity, normCapacity);
}
incTinySmallAllocation(tiny);
return;
}
if (normCapacity <= chunkSize) {
if (cache.allocateNormal(this, buf, reqCapacity, normCapacity)) {
return;
}
synchronized (this) {
allocateNormal(buf, reqCapacity, normCapacity);
++allocationsNormal;
}
} else {
allocateHuge(buf, reqCapacity);
}
}
可以看出這個方法是相當的長,但總體邏輯還算清晰,慣例先分步驟:
- 將申請內存規整化。
- 申請tiny、small級別的內存。
- 申請normal級別的內存。
- 申請huge級別的內存。
將申請內存規整化。
將內存大小規整化這個概念前面多次提到,他的作用是將內存大小向上對齊。對于512B以下大小的內存,對齊到大于申請內存的下一個16B的倍數。比如15B,會對齊到16B,41B會對齊到48B。對于大于512B的內存,對齊到大于申請內存的下一個2的冪次方,比如申請600B,會對齊到1KB,申請3KB,會對齊到4KB。
它的實現大量使用位運算,代碼如下。由于directMemoryCacheAlignment默認為0,且通常也不會設置,這里忽略了。
int normalizeCapacity(int reqCapacity) {
checkPositiveOrZero(reqCapacity, "reqCapacity");
if (reqCapacity >= chunkSize) {
return reqCapacity;
}
if (!isTiny(reqCapacity)) {
int normalizedCapacity = reqCapacity;
normalizedCapacity --;
normalizedCapacity |= normalizedCapacity >>> 1;
normalizedCapacity |= normalizedCapacity >>> 2;
normalizedCapacity |= normalizedCapacity >>> 4;
normalizedCapacity |= normalizedCapacity >>> 8;
normalizedCapacity |= normalizedCapacity >>> 16;
normalizedCapacity ++;
if (normalizedCapacity < 0) {
normalizedCapacity >>>= 1;
}
return normalizedCapacity;
}
if ((reqCapacity & 15) == 0) {
return reqCapacity;
}
return (reqCapacity & ~15) + 16;
}
首先檢驗了內存是否不是負數,否則直接拋出異常。之后判斷申請內存是否超出了ChunkSize級別,即16MB,若超出這個大小,則達到了huge級別,無需規整化。
若不是tiny級別內存,則先自減,分別與自身無符號右移1、2、4、8、16位做或運算,再自增。完成后還做了是否越界的判斷,越界時,無符號右移一位。
比如600B,二進制為0010 0101 1000,自減后變成0010 0101 0111,做完無符號右移后,變成0011 1111 1111,自增后,變成0100 0000 0000,即2^10=1024B。
若為tiny級別,&15==0表明剛好是16的倍數,直接返回。否則對15取反后,與內存做與運算,再加上16。因為15取反后,低4位為0,高位全部為1,相當于掩碼。
申請tiny、small級別的內存
在對內存規整化以后,首先需要判斷它在哪個范圍。對tiny、small級別來說采用的是 (subpageOverflowMask & normCapacity) == 0 這樣一個判斷條件,其中subpageOverflowMask = ~(pageSize - 1),默認低13位為0,其余高位為1。之后又使用 (normCapacity & 0xFFFFFE00) == 0 進一步劃分tiny和small。tiny、small,包括后續的norm,都會先嘗試用緩存分配,如果分配成功則直接返回。緩存分配留待后續。
在緩存分配失敗后,會去相應的PoolArena中的PoolSubpage數組定位到對應大小PoolSubpage的head結點。
在分配之前,先對head加鎖,因為此時PoolChunk.allocateSubpage和PoolChunk.free可能會并發修改PoolSubpage鏈表。
加鎖完成進入臨界區,迭代head的下一個非空PoolSubpage節點,調用其allocate方法進行內存分配。
在分配完成后,還需要調用其所在PoolChunk的initBufWithSubpage方法,最終會調用ByteBuf.init方法進行初始化。分配完成后,增加對應的分配計數器
若不存在非空的PoolSubpage節點,則還是需要在normal分配。
申請normal級別的內存
在分配normal級別的內存時,需要對PoolArena對象加鎖,防止其他線程同時分配內存。具體分配的代碼如下
private void allocateNormal(PooledByteBuf<T> buf, int reqCapacity, int normCapacity) {
if (q050.allocate(buf, reqCapacity, normCapacity) || q025.allocate(buf, reqCapacity, normCapacity) ||
q000.allocate(buf, reqCapacity, normCapacity) || qInit.allocate(buf, reqCapacity, normCapacity) ||
q075.allocate(buf, reqCapacity, normCapacity)) {
return;
}
// Add a new chunk.
PoolChunk<T> c = newChunk(pageSize, maxOrder, pageShifts, chunkSize);
boolean success = c.allocate(buf, reqCapacity, normCapacity);
assert success;
qInit.add(c);
}
首先嘗試在5個PoolChunkList中分配內存。PoolChunkList分配內存的相關代碼在前文已經涉及。它最終會將分配的PoolChunk放在合適使用率的PoolChunkList中。
若PoolChunkList中沒有分配成功(比如在初始狀態下,PoolChunkList中除了head節點沒有其他PoolChunk對象),在會新增一個PoolChunk,調用新增PoolChunk分配內存。分配完成并且初始化后,將PoolChunk加入qInit鏈表中,并移動到符合使用率的鏈表中。
分配成功后,會在PoolArena中將對應計數器自增。
申請huge級別內存
由于huge級別的內存過大,不適合池化管理,所以申請的是unpooled的內存。申請完huge內存后,依然進行初始化和計數。
private void allocateHuge(PooledByteBuf<T> buf, int reqCapacity) {
PoolChunk<T> chunk = newUnpooledChunk(reqCapacity);
activeBytesHuge.add(chunk.chunkSize());
buf.initUnpooled(chunk, reqCapacity);
allocationsHuge.increment();
}