Skip to content

Commit d1d498f

Browse files
author
jiangwh
committedJul 11, 2021
add netty code
1 parent 37142c0 commit d1d498f

File tree

1 file changed

+73
-2
lines changed

1 file changed

+73
-2
lines changed
 

‎netty/netty.md

+73-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
# netty的零复制处理
1+
# netty
2+
关于netty一些理解
3+
4+
## netty的零复制处理
25

36
### zero-copy
47

@@ -12,7 +15,7 @@ linux中支持zero-copy的函数:mmap、sendfile、splice。
1215

1316
```sendfile With DMA Scatter/Gather Copy```
1417

15-
## netty中的zero-copy
18+
### netty中的zero-copy
1619

1720
下面是netty中读取数据的代码与正常的应用程序并无本质区别。
1821

@@ -84,3 +87,71 @@ netty中零复制的体现,就是netty中bytebuf,bytebuf减少了应用层
8487
}
8588
```
8689

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

Comments
 (0)
Please sign in to comment.