1
- # netty的零复制处理
1
+ # netty
2
+ 关于netty一些理解
3
+
4
+ ## netty的零复制处理
2
5
3
6
### zero-copy
4
7
@@ -12,7 +15,7 @@ linux中支持zero-copy的函数:mmap、sendfile、splice。
12
15
13
16
``` sendfile With DMA Scatter/Gather Copy ```
14
17
15
- ## netty中的zero-copy
18
+ ### netty中的zero-copy
16
19
17
20
下面是netty中读取数据的代码与正常的应用程序并无本质区别。
18
21
@@ -84,3 +87,71 @@ netty中零复制的体现,就是netty中bytebuf,bytebuf减少了应用层
84
87
}
85
88
```
86
89
90
+ ## netty直接内存管理
91
+
92
+ netty直接内存是框架自身管理的,需要手动的进行alloc以及release。
93
+
94
+ ### 申请直接内存
95
+
96
+ ``` java
97
+ // 增加引用计数
98
+ // 内存track
99
+ // 申请直接内存
100
+ @Override
101
+ protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) {
102
+ PoolThreadCache cache = threadCache. get();
103
+ PoolArena<ByteBuffer > directArena = cache. directArena;
104
+
105
+ final ByteBuf buf;
106
+ if (directArena != null ) {
107
+ buf = directArena. allocate(cache, initialCapacity, maxCapacity);
108
+ } else {
109
+ buf = PlatformDependent . hasUnsafe() ?
110
+ UnsafeByteBufUtil . newUnsafeDirectByteBuf(this , initialCapacity, maxCapacity) :
111
+ new UnpooledDirectByteBuf (this , initialCapacity, maxCapacity);
112
+ }
113
+
114
+ return toLeakAwareBuffer(buf);
115
+ }
116
+
117
+ ```
118
+
119
+ ### 释放内存
120
+
121
+ ``` java
122
+ // 减少引用
123
+ // free内存
124
+ private boolean release0(int decrement) {
125
+ int rawCnt = nonVolatileRawCnt(), realCnt = toLiveRealCnt(rawCnt, decrement);
126
+ if (decrement == realCnt) {
127
+ if (refCntUpdater. compareAndSet(this , rawCnt, 1 )) {
128
+ deallocate();
129
+ return true ;
130
+ }
131
+ return retryRelease0(decrement);
132
+ }
133
+ return releaseNonFinal0(decrement, rawCnt, realCnt);
134
+ }
135
+ ```
136
+
137
+
138
+
139
+ ### 代码技巧
140
+
141
+ ``` java
142
+ public boolean close(T trackedObject) {
143
+ // Ensure that the object that was tracked is the same as the one that was passed to close(...).
144
+ assert trackedHash == System . identityHashCode(trackedObject);
145
+
146
+ try {
147
+ return close();
148
+ } finally {
149
+ // This method will do `synchronized(trackedObject)` and we should be sure this will not cause deadlock.
150
+ // It should not, because somewhere up the callstack should be a (successful) `trackedObject.release`,
151
+ // therefore it is unreasonable that anyone else, anywhere, is holding a lock on the trackedObject.
152
+ // (Unreasonable but possible, unfortunately.)
153
+ reachabilityFence0(trackedObject);
154
+ }
155
+ }
156
+ ```
157
+
0 commit comments