Netty源码之解码中两种数据积累器(Cumulator)的区别
生活随笔
收集整理的這篇文章主要介紹了
Netty源码之解码中两种数据积累器(Cumulator)的区别
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
上一篇隨筆中已經(jīng)介紹了解碼核心工作流程,里面有個(gè)數(shù)據(jù)積累器的存在(Cumulator),其實(shí)解碼中有兩種Cumulator,那他們的區(qū)別是什么呢?
還是先打開ByteToMessageDecoder的channelRead();
點(diǎn)進(jìn)去查看cumulate()實(shí)現(xiàn)
又是一個(gè)抽象方法,看實(shí)現(xiàn)不難發(fā)現(xiàn)它有兩種實(shí)現(xiàn)方式
兩種實(shí)現(xiàn)分別為:MERGE_CUMULATOR(默認(rèn)的):采用的是內(nèi)存復(fù)制,先擴(kuò)容空間,再追加數(shù)據(jù)
public static final Cumulator MERGE_CUMULATOR = new Cumulator() {
@Override
public ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) {
try {
final ByteBuf buffer;
if (cumulation.writerIndex() > cumulation.maxCapacity() - in.readableBytes()
|| cumulation.refCnt() > 1 || cumulation.isReadOnly()) {
// Expand cumulation (by replace it) when either there is not more room in the buffer
// or if the refCnt is greater then 1 which may happen when the user use slice().retain() or
// duplicate().retain() or if its read-only.
//
// See:
// - https://github.com/netty/netty/issues/2327
// - https://github.com/netty/netty/issues/1764
buffer = expandCumulation(alloc, cumulation, in.readableBytes());
} else {
buffer = cumulation;
}
buffer.writeBytes(in);
return buffer;
} finally {
// We must release in in all cases as otherwise it may produce a leak if writeBytes(...) throw
// for whatever release (for example because of OutOfMemoryError)
in.release();
}
}
};
第二種 :COMPOSITE_CUMULATOR :不是復(fù)制而是組合,先擴(kuò)容,如果數(shù)據(jù)夠了的話就直接把數(shù)據(jù)給組合起來,避免了內(nèi)存復(fù)制
public static final Cumulator COMPOSITE_CUMULATOR = new Cumulator() {
@Override
public ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) {
ByteBuf buffer;
try {
if (cumulation.refCnt() > 1) {
// Expand cumulation (by replace it) when the refCnt is greater then 1 which may happen when the
// user use slice().retain() or duplicate().retain().
//
// See:
// - https://github.com/netty/netty/issues/2327
// - https://github.com/netty/netty/issues/1764
buffer = expandCumulation(alloc, cumulation, in.readableBytes());
buffer.writeBytes(in);
} else {
CompositeByteBuf composite;
if (cumulation instanceof CompositeByteBuf) {
composite = (CompositeByteBuf) cumulation;
} else {
composite = alloc.compositeBuffer(Integer.MAX_VALUE);
composite.addComponent(true, cumulation);
}
composite.addComponent(true, in);
in = null;
buffer = composite;
}
return buffer;
} finally {
if (in != null) {
// We must release if the ownership was not transferred as otherwise it may produce a leak if
// writeBytes(...) throw for whatever release (for example because of OutOfMemoryError).
in.release();
}
}
}
};
我只想做的更好,僅此而已
總結(jié)
以上是生活随笔為你收集整理的Netty源码之解码中两种数据积累器(Cumulator)的区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python画一个祝福别人生日快乐_分享
- 下一篇: opencv —— resize、pyr