Netty source code analysis -- implementation principle of poolsubpage

Waste 2020-11-08 21:03:49
netty source code analysis implementation


The previous article said PoolChunk How to manage Normal Memory block , This article shares PoolSubpage How to manage Small Memory block .
Source code analysis is based on Netty 4.1.52

Memory management algorithm

PoolSubpage Responsible for managing the Small Memory block . One PoolSubpage Memory block in size All the same , The size Corresponding SizeClasses#sizeClasses An index of the table index.
The newly created PoolSubpage Must be added to PoolArena#smallSubpagePools[index] In the list .
PoolArena#smallSubpagePools It's a PoolSubpage Array , Every element in an array is a PoolSubpage Linked list ,PoolSubpage You can go through next,prev Make up a list .
Interested students can refer to 《 Memory alignment class SizeClasses》.

Be careful ,Small Memory size Not necessarily less than pageSize( The default is 8K)
Default Small Memory size <= 28672(28KB)
About Normal Memory block ,Small Memory block ,pageSize, May refer to 《PoolChunk Realization principle 》.

PoolSubpage It's actually PoolChunk One of them Normal Memory block , The size is the memory block it manages size And pageSize Minimum common multiple .
PoolSubpage Use bitmap to manage memory blocks .
PoolSubpage#bitmap It's a long Array , Each of them long Each of the elements bit Bits can represent whether a block of memory is used or not .

Memory allocation

Distribute Small The memory block has two steps

  1. PoolChunk The distribution of PoolSubpage.

If PoolArena#smallSubpagePools There is already a corresponding PoolSubpage buffer , Then this step is not needed .

  1. PoolSubpage Allocate memory blocks on

PoolChunk#allocateSubpage

private long allocateSubpage(int sizeIdx) {
// #1
PoolSubpage<T> head = arena.findSubpagePoolHead(sizeIdx);
synchronized (head) {
//allocate a new run
// #2
int runSize = calculateRunSize(sizeIdx);
//runSize must be multiples of pageSize
// #3
long runHandle = allocateRun(runSize);
if (runHandle < 0) {
return -1;
}
// #4
int runOffset = runOffset(runHandle);
int elemSize = arena.sizeIdx2size(sizeIdx);
PoolSubpage<T> subpage = new PoolSubpage<T>(head, this, pageShifts, runOffset,
runSize(pageShifts, runHandle), elemSize);
subpages[runOffset] = subpage;
// #5
return subpage.allocate();
}
}

#1 This modification involves PoolArena#smallSubpagePools Medium PoolSubpage Linked list , Synchronous operation is required
#2 Calculating memory blocks size and pageSize Minimum common multiple
#3 Allocate one Normal Memory block , As PoolSubpage The underlying memory block of , The size is Small Memory block size and pageSize Minimum common multiple
#4 structure PoolSubpage
runOffset, namely Normal Memory block offset , It's time to PoolSubpage Throughout Chunk Offset in
elemSize,Small Memory block size
#5 stay subpage Allocate memory blocks on

PoolSubpage(PoolSubpage<T> head, PoolChunk<T> chunk, int pageShifts, int runOffset, int runSize, int elemSize) {
// #1
this.chunk = chunk;
this.pageShifts = pageShifts;
this.runOffset = runOffset;
this.runSize = runSize;
this.elemSize = elemSize;
bitmap = new long[runSize >>> 6 + LOG2_QUANTUM]; // runSize / 64 / QUANTUM
init(head, elemSize);
}
void init(PoolSubpage<T> head, int elemSize) {
doNotDestroy = true;
if (elemSize != 0) {
// #2
maxNumElems = numAvail = runSize / elemSize;
nextAvail = 0;
bitmapLength = maxNumElems >>> 6;
if ((maxNumElems & 63) != 0) {
bitmapLength ++;
}
for (int i = 0; i < bitmapLength; i ++) {
bitmap[i] = 0;
}
}
// #3
addToPool(head);
}

#1 bitmap The length is runSize / 64 / QUANTUM, from 《 Memory alignment class SizeClasses》 You can see ,runSize All are 2^LOG2_QUANTUM Multiple .

#2
elemSize: The size of each memory block
maxNumElems: Number of memory blocks
bitmapLength:bitmap The use of long Element number , Use bitmap Some of the elements in are enough to manage all memory blocks .
(maxNumElems & 63) != 0, representative maxNumElems Not divisible 64, therefore bitmapLength To add 1, Used to manage the remaining blocks of memory .
#3 Add to PoolSubpage In the list

Previous analysis 《Netty Memory pool and PoolArena》 Said in , stay PoolArena The distribution of Small Memory block , First of all, from PoolArena#smallSubpagePools Find the corresponding PoolSubpage​. If you find it , Directly from the PoolSubpage​ Allocate memory on . otherwise , Allocate one Normal Memory block , establish PoolSubpage​, Then allocate memory blocks on it .

PoolSubpage#allocate

long allocate() {
// #1
if (numAvail == 0 || !doNotDestroy) {
return -1;
}
// #2
final int bitmapIdx = getNextAvail();
// #3
int q = bitmapIdx >>> 6;
int r = bitmapIdx & 63;
assert (bitmap[q] >>> r & 1) == 0;
bitmap[q] |= 1L << r;
// #4
if (-- numAvail == 0) {
removeFromPool();
}
// #5
return toHandle(bitmapIdx);
}

#1 No memory block available , Allocation failed . Usually PoolSubpage After the assignment is completed, it will be transferred from PoolArena#smallSubpagePools Remove , It's no longer the time to PoolSubpage Allocate memory on , So it doesn't usually happen .
#2 Get the next available block of memory bit Subscript
#3 Set the corresponding bit by 1, That is to say, it has been used
bitmapIdx >>> 6, Get the memory block in bitmap No q Elements
bitmapIdx & 63, Getting the memory block is bitmap No q The number of elements r individual bit position
bitmap[q] |= 1L << r, take bitmap No q The number of elements r individual bit Bit is set to 1, Indicates used
#4 All memory blocks have been allocated , From the PoolArena Remove .
#5 toHandle Convert to final handle

private int getNextAvail() {
int nextAvail = this.nextAvail;
if (nextAvail >= 0) {
this.nextAvail = -1;
return nextAvail;
}
return findNextAvail();
}

nextAvail Is the initial value or free The value released when .
If nextAvail There is , This value is returned directly when it is set to unavailable .
If it doesn't exist , call findNextAvail Find the next available block of memory .

private int findNextAvail() {
final long[] bitmap = this.bitmap;
final int bitmapLength = this.bitmapLength;
// #1
for (int i = 0; i < bitmapLength; i ++) {
long bits = bitmap[i];
if (~bits != 0) {
return findNextAvail0(i, bits);
}
}
return -1;
}
private int findNextAvail0(int i, long bits) {
final int maxNumElems = this.maxNumElems;
final int baseVal = i << 6;
// #2
for (int j = 0; j < 64; j ++) {
if ((bits & 1) == 0) {
int val = baseVal | j;
if (val < maxNumElems) {
return val;
} else {
break;
}
}
bits >>>= 1;
}
return -1;
}

#1 Traverse bitmap,~bits != 0, It means that there is a bit Not for 1, That is, there are blocks of available memory .
#2 Traverse 64 individual bit position ,
(bits & 1) == 0, Check the lowest bit Whether a is 0( You can use ), by 0 Then return to val.
val be equal to (i << 6) | j, namely i * 64 + j, The bit Bit in bitmap How many bit position .
bits >>>= 1, Moves to the right one , Deal with the next bit position .

Memory free

Release Small Memory blocks can have two steps

  1. Release PoolSubpage On the memory block
  2. If PoolSubpage All memory blocks in have been released , From Chunk Release the PoolSubpage, Simultaneously from PoolArena#smallSubpagePools Remove it .

PoolSubpage#free

boolean free(PoolSubpage<T> head, int bitmapIdx) {
if (elemSize == 0) {
return true;
}
// #1
int q = bitmapIdx >>> 6;
int r = bitmapIdx & 63;
assert (bitmap[q] >>> r & 1) != 0;
bitmap[q] ^= 1L << r;
setNextAvail(bitmapIdx);
// #2
if (numAvail ++ == 0) {
addToPool(head);
return true;
}
// #3
if (numAvail != maxNumElems) {
return true;
} else {
// #4
if (prev == next) {
// Do not remove if this subpage is the only one left in the pool.
return true;
}
// #5
doNotDestroy = false;
removeFromPool();
return false;
}
}

#1 To the corresponding bit Bit is set to use
#2 stay PoolSubpage When all blocks of memory are used , A block of memory has been released , Now rejoin PoolArena in .
#3 Not completely released , That is, there are also allocated memory blocks , return true
#4 Here comes the logic , It's dealing with scenarios where all memory blocks have been completely released .
PoolArena#smallSubpagePools The linked list forms a bidirectional list , There is only... In the list head And the current PoolSubpage when , At present PoolSubpage Of prev,next All point to head.
Now ​PoolSubpage yes PoolArena The last one in the list PoolSubpage, Don't release it PoolSubpage, So that the next time you apply for memory, you can directly from the PoolSubpage The distribution of .
#5 from PoolArena Remove , And back to false, At this time PoolChunk The corresponding will be released Page node .

void free(long handle, int normCapacity, ByteBuffer nioBuffer) {
if (isSubpage(handle)) {
// #1
int sizeIdx = arena.size2SizeIdx(normCapacity);
PoolSubpage<T> head = arena.findSubpagePoolHead(sizeIdx);
PoolSubpage<T> subpage = subpages[runOffset(handle)];
assert subpage != null && subpage.doNotDestroy;
synchronized (head) {
// #2
if (subpage.free(head, bitmapIdx(handle))) {
//the subpage is still used, do not free it
return;
}
}
}
// #3
...
}

#1
lookup head node , Sync
#2
call subpage#free Release Small Memory block
If subpage#free return false, Will continue down , This will release PoolSubpage The whole memory block , otherwise , Don't release PoolSubpage Memory block .
#3 Release Normal Memory block , Is to release PoolSubpage The whole memory block . This part can refer to 《PoolChunk Realization principle 》.

If you think this article is good , Welcome to my WeChat official account. , The series is being updated . Your concern is the driving force of my persistence !

版权声明
本文为[Waste]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云