- 浏览: 999761 次
-
文章分类
- 全部博客 (428)
- Hadoop (2)
- HBase (1)
- ELK (1)
- ActiveMQ (13)
- Kafka (5)
- Redis (14)
- Dubbo (1)
- Memcached (5)
- Netty (56)
- Mina (34)
- NIO (51)
- JUC (53)
- Spring (13)
- Mybatis (17)
- MySQL (21)
- JDBC (12)
- C3P0 (5)
- Tomcat (13)
- SLF4J-log4j (9)
- P6Spy (4)
- Quartz (12)
- Zabbix (7)
- JAVA (9)
- Linux (15)
- HTML (9)
- Lucene (0)
- JS (2)
- WebService (1)
- Maven (4)
- Oracle&MSSQL (14)
- iText (11)
- Development Tools (8)
- UTILS (4)
- LIFE (8)
最新评论
-
Donald_Draper:
Donald_Draper 写道刘落落cici 写道能给我发一 ...
DatagramChannelImpl 解析三(多播) -
Donald_Draper:
刘落落cici 写道能给我发一份这个类的源码吗Datagram ...
DatagramChannelImpl 解析三(多播) -
lyfyouyun:
请问楼主,执行消息发送的时候,报错:Transport sch ...
ActiveMQ连接工厂、连接详解 -
ezlhq:
关于 PollArrayWrapper 状态含义猜测:参考 S ...
WindowsSelectorImpl解析一(FdMap,PollArrayWrapper) -
flyfeifei66:
打算使用xmemcache作为memcache的客户端,由于x ...
Memcached分布式客户端(Xmemcached)
netty 通道接口定义:http://donald-draper.iteye.com/blog/2392740
netty 抽象通道初始化:http://donald-draper.iteye.com/blog/2392801
netty 抽象Unsafe定义:http://donald-draper.iteye.com/blog/2393053
netty 通道Outbound缓冲区:http://donald-draper.iteye.com/blog/2393098
netty 抽象通道后续:http://donald-draper.iteye.com/blog/2393166
netty 抽象nio通道:http://donald-draper.iteye.com/blog/2393269
netty 抽象nio字节通道:http://donald-draper.iteye.com/blog/2393323
netty 抽象nio消息通道:http://donald-draper.iteye.com/blog/2393364
netty NioServerSocketChannel解析:http://donald-draper.iteye.com/blog/2393443
netty 通道配置接口定义:http://donald-draper.iteye.com/blog/2393484
netty 默认通道配置初始化:http://donald-draper.iteye.com/blog/2393504
netty 默认通道配置后续:http://donald-draper.iteye.com/blog/2393510
netty 字节buf定义:http://donald-draper.iteye.com/blog/2393813
netty 资源泄漏探测器:http://donald-draper.iteye.com/blog/2393940
引言
本打算上一文章看一抽象字节buf,但中途遇到了资源泄漏探测器,就简单分析了资源泄漏探测器,今天我们回到抽象字节buf,先来回顾字节buf接口的定义:
对象引用计数器ReferenceCounted,主要记录对象的引用数量,当引用数量为0时,表示可以回收对象,在调试模式下,如果发现对象出现内存泄漏,可以用touch方法记录操作的相关信息,通过ResourceLeakDetector获取操作的相关信息,以便分析内存泄漏的原因。
字节缓存ByteBuf继承了对象引用计数器ReferenceCounted,拥有一个最大容量限制,如果用户尝试用 #capacity(int)和 #ensureWritable(int)方法,增加buf容量超过最大容量,将会抛出非法参数异常;字节buf有两个索引,一个为读索引readerIndex,一个为写索引writerIndex,读索引不能大于写索引,写索引不能小于读索引,buf可读字节数为writerIndex - readerIndex,buf可写字节数为capacity - writerIndex,buf可写的最大字节数为maxCapacity - writerIndex;
可以使用markReader/WriterIndex标记当前buf读写索引位置,resetReader/WriterIndex方法可以重回先前标记的索引位置;
当内存空间负载过度时,我们可以使用discardReadBytes丢弃一些数据,以节省空间;
我们可以使用ensureWritable检测当buf是否有足够的空间写数据;
提供了getBytes方法,可以将buf中的数据转移到目的ByteBuf,Byte数组,Nio字节buf ByteBuffer,OutputStream,聚集字节通道
GatheringByteChannel和文件通道FileChannel中,这些方法不会修改当前buf读写索引,具体是否修改目的对象索引或位置,见java doc 描述。
提供了setBytes方法,可以将源ByteBuf,Byte数组,Nio字节buf ByteBuffer,InputputStream,分散字节通道ScatteringByteChannel和文件通道FileChannel中的数据转移到当前buf中,这些方法不会修改当前buf的读写索引,至于源对象索引或位置,见java doc 描述。
提供了readBytes方法,可以将buf中的数据转移到目的ByteBuf,Byte数组,Nio字节buf ByteBuffer,OutputStream,聚集字节通道GatheringByteChannel和文件通道FileChannel中,这些方法具体会会修改当前buf读索引,至于会不会修改源对象索引或位置,见java doc 描述。
提供了writeBytes方法,可以将源ByteBuf,Byte数组,Nio字节buf ByteBuffer,
InputputStream,分散字节通道ScatteringByteChannel和文件通道FileChannel中的数据写到当前buf中,这些方法会修改当前buf的写索引,至于会不会修改源对象索引或位置,见java
doc 描述。
set*原始类型方法不会修改读写索引;
get*原始类型方法不会修改读写索引;
write*原始类型方法会修改写索引;
read*原始类型方法,会修改读索引;
字节buf中的set/get*方法不会修改当前buf的读写索引,而write*修改写索引,read*会修改读索引;
提供了copy,slice和retainSlice,duplicate和retainedDuplicate方法,用于拷贝,切割,复制当前buf数据,retained*方法会增加buf的
引用计数器;
提供nioBuffer和nioBuffers方法,用于包装当前buf可读数据为java nio ByteBuffer和ByteBuffer数组。
今天我们来看一下抽象字节buf的定义
从上面来看,字节buf内部有两个索引,一个读索引,一个写索引,两个索引标记,即读写索引对应的标记,buf的最大容量为maxCapacity;buf的构造,主要是初始化最大容量。
先来看读写索引相关的操作,很简单,看一下就了。
字节buf,读写索引设值获取、标记重置相关方法:
来看设置读写索引方法
再来看丢弃已经读过的字节数据:
从上面可以看出,丢弃已读数据方法discardReadBytes,丢弃buf数据时,只修改读写索引和相应的标记,
并不删除数据。
再来看,根据负载丢弃数据方法:
来看get*方法:
来看获取一个字节:
检查索引是否越界
//MathUtil
再看获取一个int值:
其他get原始类型方法,思路基本相同;
来看getBytes(*)方法:
字节buf接口定义中:
从上面可以看出,getBytes(...,ByteBuf,...)方法不会修改当前buf读写索引,会修改目的buf的写索引。getBytes(...,byte[],...)方法不会修改当前buf读写索引。
//ByteBufUtil
回到抽象字节buf,来看set方法:
其他set原始类型方法,思路基本相同。
再来看setBytes(*)系列方法:
//ByteBuf
从上面可以看出,setBytes(...,ByteBuf,...)方法不会修改当前buf读写索引,会修改源buf的读索引。setBytes(...,byte[],...)方法不会修改当前buf读写索引。
来set写字符序列
//ByteBufUtil
回到抽象字节buf,来看read*相关方法:
先来看读一个字节数据
其他get*原始类型方法,思路基本相同
来看readBytes(*)相关方法:
从上面来看readBytes(byte[],...),会修改当前buf的读索引
//ByteBuf
//ByteBuf
//ByteBuf
//ByteBuf
从上面可以看出,read*原始类型方法会修改当前buf读索引,readBytes(...,ByteBuf,...)方法会修改当前buf读索引,同时会修改目的buf的写索引,readBytes(...,byte[],...)方法会修改当前buf读索引。read*操作实际委托个get*的相关操作,同时更新buf读索引。
再来看readSlice相关方法
//UnpooledSlicedByteBuf
//AbstractUnpooledSlicedByteBuf,可以理解为字节buf的静态代理
//AbstractDerivedByteBuf,可以理解实现了引用计数器的抽象字节buf
//ByteBuf
从上面可以看出retainedSlice和slice方法返回则的字节buf,实际为字节buf底层unwrap buf,
可以理解为字节buf的快照或引用,数据更改相互影响,retainedSlice方法会增加字节buf的引用计数器。
再来看读部分数据到字节序列
再来看skipBytes方法
再来看write*相关方法:
再来看写int
其他write*原始类型方法,思路基本相同;
再来看writeBytes相关方法
将字节数组数据写到当前buf
将字节buf数据写到当前buf
再来看将nio 字节buf,InputStream,ScatteringByteChannel,FileChannel中的数据写到
当前buf
//ByteBuf
//ByteBuf
//ByteBuf
//ByteBuf
从上面可以看出write*原始类型方法会修改当前buf写索引,writeBytes(...,ByteBuf,...)方法会修改当前buf写索引,同时会修改目的buf的读索引,writeBytes(...,byte[],...)方法会修改当前buf写索引。write*操作实际委托个set*的相关操作,同时更新buf写索引。
再来看复制方法:
//ByteBuf
slice和retainedSlice相关的方法,我们在前面已说,这里仅仅展示一下:
来看完全复制duplicate
//可以理解为buf的静态代理
从上面可以看出:retainedDuplicate和duplicate方法返回则的字节buf,实际为字节buf底层unwrap buf,可以理解为字节buf的快照或引用,数据更改相互影响,retainedDuplicate方法会增加字节buf的引用计数器。
再来看转化nio ByteBuffer
//ByteBuf
public abstract ByteBuffer[] nioBuffers(int index, int length);
总结:
字节buf内部有两个索引,一个读索引,一个写索引,两个索引标记,即读写索引对应的标记,buf的最大容量为maxCapacity;buf的构造,主要是初始化最大容量。
弃已读数据方法discardReadBytes,丢弃buf数据时,只修改读写索引和相应的标记,并不删除数据。
get*原始类型方法不会修改当前buf读写索引,getBytes(...,ByteBuf,...)方法不会修改当前buf读写索引,会修改目的buf的写索引。getBytes(...,byte[],...)方法不会修改当前buf读写索引。
set*原始类型方法不会修改当前buf读写索引,setBytes(...,ByteBuf,...)方法不会修改当前buf读写索引,会修改源buf的读索引。setBytes(...,byte[],...)方法不会修改当前buf读写索引。
read*原始类型方法会修改当前buf读索引,readBytes(...,ByteBuf,...)方法会修改当前buf读索引,同时会修改目的buf的写索引,readBytes(...,byte[],...)方法会修改当前buf读索引。
read*操作实际委托个get*的相关操作,同时更新buf读索引。
跳过length长度的字节,只更新读索引,不删除实际buf数据。
retainedSlice和slice方法返回则的字节buf,实际为字节buf底层unwrap buf,可以理解为字节buf的快照或引用,数据更改相互影响,retainedSlice方法会增加字节buf的引用计数器。
write*原始类型方法会修改当前buf写索引,writeBytes(...,ByteBuf,...)方法会修改当前buf写索引,同时会修改目的buf的读索引,readBytes(...,byte[],...)方法会修改当前buf写索引。
write*操作实际委托个set*的相关操作,同时更新buf写索引。
retainedDuplicate和duplicate方法返回则的字节buf,实际为字节buf底层unwrap buf,可以理解为字节buf的快照或引用,数据更改相互影响,retainedDuplicate方法会增加字节buf的引用计数器。
附:
//ByteBufUtil
/
//ByteProcessor
//遍历buf所有字节,调用处理器,处理
升序方式
倒序方式
netty 抽象通道初始化:http://donald-draper.iteye.com/blog/2392801
netty 抽象Unsafe定义:http://donald-draper.iteye.com/blog/2393053
netty 通道Outbound缓冲区:http://donald-draper.iteye.com/blog/2393098
netty 抽象通道后续:http://donald-draper.iteye.com/blog/2393166
netty 抽象nio通道:http://donald-draper.iteye.com/blog/2393269
netty 抽象nio字节通道:http://donald-draper.iteye.com/blog/2393323
netty 抽象nio消息通道:http://donald-draper.iteye.com/blog/2393364
netty NioServerSocketChannel解析:http://donald-draper.iteye.com/blog/2393443
netty 通道配置接口定义:http://donald-draper.iteye.com/blog/2393484
netty 默认通道配置初始化:http://donald-draper.iteye.com/blog/2393504
netty 默认通道配置后续:http://donald-draper.iteye.com/blog/2393510
netty 字节buf定义:http://donald-draper.iteye.com/blog/2393813
netty 资源泄漏探测器:http://donald-draper.iteye.com/blog/2393940
引言
本打算上一文章看一抽象字节buf,但中途遇到了资源泄漏探测器,就简单分析了资源泄漏探测器,今天我们回到抽象字节buf,先来回顾字节buf接口的定义:
对象引用计数器ReferenceCounted,主要记录对象的引用数量,当引用数量为0时,表示可以回收对象,在调试模式下,如果发现对象出现内存泄漏,可以用touch方法记录操作的相关信息,通过ResourceLeakDetector获取操作的相关信息,以便分析内存泄漏的原因。
字节缓存ByteBuf继承了对象引用计数器ReferenceCounted,拥有一个最大容量限制,如果用户尝试用 #capacity(int)和 #ensureWritable(int)方法,增加buf容量超过最大容量,将会抛出非法参数异常;字节buf有两个索引,一个为读索引readerIndex,一个为写索引writerIndex,读索引不能大于写索引,写索引不能小于读索引,buf可读字节数为writerIndex - readerIndex,buf可写字节数为capacity - writerIndex,buf可写的最大字节数为maxCapacity - writerIndex;
可以使用markReader/WriterIndex标记当前buf读写索引位置,resetReader/WriterIndex方法可以重回先前标记的索引位置;
当内存空间负载过度时,我们可以使用discardReadBytes丢弃一些数据,以节省空间;
我们可以使用ensureWritable检测当buf是否有足够的空间写数据;
提供了getBytes方法,可以将buf中的数据转移到目的ByteBuf,Byte数组,Nio字节buf ByteBuffer,OutputStream,聚集字节通道
GatheringByteChannel和文件通道FileChannel中,这些方法不会修改当前buf读写索引,具体是否修改目的对象索引或位置,见java doc 描述。
提供了setBytes方法,可以将源ByteBuf,Byte数组,Nio字节buf ByteBuffer,InputputStream,分散字节通道ScatteringByteChannel和文件通道FileChannel中的数据转移到当前buf中,这些方法不会修改当前buf的读写索引,至于源对象索引或位置,见java doc 描述。
提供了readBytes方法,可以将buf中的数据转移到目的ByteBuf,Byte数组,Nio字节buf ByteBuffer,OutputStream,聚集字节通道GatheringByteChannel和文件通道FileChannel中,这些方法具体会会修改当前buf读索引,至于会不会修改源对象索引或位置,见java doc 描述。
提供了writeBytes方法,可以将源ByteBuf,Byte数组,Nio字节buf ByteBuffer,
InputputStream,分散字节通道ScatteringByteChannel和文件通道FileChannel中的数据写到当前buf中,这些方法会修改当前buf的写索引,至于会不会修改源对象索引或位置,见java
doc 描述。
set*原始类型方法不会修改读写索引;
get*原始类型方法不会修改读写索引;
write*原始类型方法会修改写索引;
read*原始类型方法,会修改读索引;
字节buf中的set/get*方法不会修改当前buf的读写索引,而write*修改写索引,read*会修改读索引;
提供了copy,slice和retainSlice,duplicate和retainedDuplicate方法,用于拷贝,切割,复制当前buf数据,retained*方法会增加buf的
引用计数器;
提供nioBuffer和nioBuffers方法,用于包装当前buf可读数据为java nio ByteBuffer和ByteBuffer数组。
今天我们来看一下抽象字节buf的定义
package io.netty.buffer; import io.netty.util.ByteProcessor; import io.netty.util.CharsetUtil; import io.netty.util.IllegalReferenceCountException; import io.netty.util.ResourceLeakDetector; import io.netty.util.ResourceLeakDetectorFactory; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.StringUtil; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; import java.nio.charset.Charset; import static io.netty.util.internal.MathUtil.isOutOfBounds; /** * A skeletal implementation of a buffer. */ public abstract class AbstractByteBuf extends ByteBuf { private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractByteBuf.class); private static final String PROP_MODE = "io.netty.buffer.bytebuf.checkAccessible"; private static final boolean checkAccessible;//访问buf时,是否可需要检查 static { checkAccessible = SystemPropertyUtil.getBoolean(PROP_MODE, true); if (logger.isDebugEnabled()) { logger.debug("-D{}: {}", PROP_MODE, checkAccessible); } } //内存泄漏探测器 static final ResourceLeakDetector<ByteBuf> leakDetector = ResourceLeakDetectorFactory.instance().newResourceLeakDetector(ByteBuf.class); int readerIndex;//读索引 int writerIndex;//写索引 private int markedReaderIndex;//读索引标记 private int markedWriterIndex;//写索引标记 private int maxCapacity;//最大容量 protected AbstractByteBuf(int maxCapacity) { if (maxCapacity < 0) { throw new IllegalArgumentException("maxCapacity: " + maxCapacity + " (expected: >= 0)"); } this.maxCapacity = maxCapacity; }: }
从上面来看,字节buf内部有两个索引,一个读索引,一个写索引,两个索引标记,即读写索引对应的标记,buf的最大容量为maxCapacity;buf的构造,主要是初始化最大容量。
先来看读写索引相关的操作,很简单,看一下就了。
字节buf,读写索引设值获取、标记重置相关方法:
@Override public boolean isReadOnly() { return false; } @SuppressWarnings("deprecation") @Override public ByteBuf asReadOnly() { if (isReadOnly()) { return this; } return Unpooled.unmodifiableBuffer(this); } @Override public int maxCapacity() { return maxCapacity; } protected final void maxCapacity(int maxCapacity) { this.maxCapacity = maxCapacity; } @Override public int readerIndex() { return readerIndex; } @Override public ByteBuf readerIndex(int readerIndex) { if (readerIndex < 0 || readerIndex > writerIndex) { throw new IndexOutOfBoundsException(String.format( "readerIndex: %d (expected: 0 <= readerIndex <= writerIndex(%d))", readerIndex, writerIndex)); } this.readerIndex = readerIndex; return this; } @Override public int writerIndex() { return writerIndex; } @Override public ByteBuf writerIndex(int writerIndex) { if (writerIndex < readerIndex || writerIndex > capacity()) { throw new IndexOutOfBoundsException(String.format( "writerIndex: %d (expected: readerIndex(%d) <= writerIndex <= capacity(%d))", writerIndex, readerIndex, capacity())); } this.writerIndex = writerIndex; return this; } @Override public ByteBuf clear() { readerIndex = writerIndex = 0; return this; } @Override public boolean isReadable() { return writerIndex > readerIndex; } @Override public boolean isReadable(int numBytes) { return writerIndex - readerIndex >= numBytes; } @Override public boolean isWritable() { return capacity() > writerIndex; } @Override public boolean isWritable(int numBytes) { return capacity() - writerIndex >= numBytes; } @Override public int readableBytes() { return writerIndex - readerIndex; } @Override public int writableBytes() { return capacity() - writerIndex; } @Override public int maxWritableBytes() { return maxCapacity() - writerIndex; } @Override public ByteBuf markReaderIndex() { markedReaderIndex = readerIndex; return this; } @Override public ByteBuf resetReaderIndex() { readerIndex(markedReaderIndex); return this; } @Override public ByteBuf markWriterIndex() { markedWriterIndex = writerIndex; return this; } @Override public ByteBuf resetWriterIndex() { writerIndex = markedWriterIndex; return this; }
来看设置读写索引方法
@Override public ByteBuf setIndex(int readerIndex, int writerIndex) { if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > capacity()) { throw new IndexOutOfBoundsException(String.format( "readerIndex: %d, writerIndex: %d (expected: 0 <= readerIndex <= writerIndex <= capacity(%d))", readerIndex, writerIndex, capacity())); } setIndex0(readerIndex, writerIndex); return this; } final void setIndex0(int readerIndex, int writerIndex) { this.readerIndex = readerIndex; this.writerIndex = writerIndex; }
再来看丢弃已经读过的字节数据:
@Override public ByteBuf discardReadBytes() { ensureAccessible(); if (readerIndex == 0) { return this; } if (readerIndex != writerIndex) { //更新索引 setBytes(0, this, readerIndex, writerIndex - readerIndex); writerIndex -= readerIndex; ////更新读写索引标记 adjustMarkers(readerIndex); readerIndex = 0; } else { adjustMarkers(readerIndex); writerIndex = readerIndex = 0; } return this; } /** * Should be called by every method that tries to access the buffers content to check * if the buffer was released before. 确保buf可以访问 */ protected final void ensureAccessible() { if (checkAccessible && refCnt() == 0) { throw new IllegalReferenceCountException(0); } } //更新读写索引标记 protected final void adjustMarkers(int decrement) { int markedReaderIndex = this.markedReaderIndex; if (markedReaderIndex <= decrement) { this.markedReaderIndex = 0; int markedWriterIndex = this.markedWriterIndex; if (markedWriterIndex <= decrement) { this.markedWriterIndex = 0; } else { this.markedWriterIndex = markedWriterIndex - decrement; } } else { this.markedReaderIndex = markedReaderIndex - decrement; markedWriterIndex -= decrement; } }
从上面可以看出,丢弃已读数据方法discardReadBytes,丢弃buf数据时,只修改读写索引和相应的标记,
并不删除数据。
再来看,根据负载丢弃数据方法:
@Override public ByteBuf discardSomeReadBytes() { ensureAccessible(); if (readerIndex == 0) { return this; } if (readerIndex == writerIndex) { //读写索引相等,则更新读写索引为0 adjustMarkers(readerIndex); writerIndex = readerIndex = 0; return this; } if (readerIndex >= capacity() >>> 1) { //丢弃已读的数据,与discardReadBytes方法作用相同 setBytes(0, this, readerIndex, writerIndex - readerIndex); writerIndex -= readerIndex; adjustMarkers(readerIndex); readerIndex = 0; } return this; }
来看get*方法:
来看获取一个字节:
@Override public byte getByte(int index) { checkIndex(index); return _getByte(index); } //待子类扩展 protected abstract byte _getByte(int index);
检查索引是否越界
protected final void checkIndex(int index) { checkIndex(index, 1); } protected final void checkIndex(int index, int fieldLength) { ensureAccessible(); checkIndex0(index, fieldLength); } final void checkIndex0(int index, int fieldLength) { if (isOutOfBounds(index, fieldLength, capacity())) { throw new IndexOutOfBoundsException(String.format( "index: %d, length: %d (expected: range(0, %d))", index, fieldLength, capacity())); } }
//MathUtil
package io.netty.util.internal; /** * Math utility methods. */ public final class MathUtil { /** * Determine if the requested {@code index} and {@code length} will fit within {@code capacity}. * @param index The starting index. * @param length The length which will be utilized (starting from {@code index}). * @param capacity The capacity that {@code index + length} is allowed to be within. * @return {@code true} if the requested {@code index} and {@code length} will fit within {@code capacity}. * {@code false} if this would result in an index out of bounds exception. */ public static boolean isOutOfBounds(int index, int length, int capacity) { return (index | length | (index + length) | (capacity - (index + length))) < 0; } ... }
再看获取一个int值:
@Override public int getInt(int index) { checkIndex(index, 4); return _getInt(index); } protected abstract int _getInt(int index);
其他get原始类型方法,思路基本相同;
来看getBytes(*)方法:
@Override public ByteBuf getBytes(int index, ByteBuf dst) { getBytes(index, dst, dst.writableBytes()); return this; } @Override public ByteBuf getBytes(int index, ByteBuf dst, int length) { getBytes(index, dst, dst.writerIndex(), length); //更新目的buf索引 dst.writerIndex(dst.writerIndex() + length); return this; } @Override public ByteBuf getBytes(int index, byte[] dst) { getBytes(index, dst, 0, dst.length); return this; }
字节buf接口定义中:
public abstract ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length); public abstract ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length);
从上面可以看出,getBytes(...,ByteBuf,...)方法不会修改当前buf读写索引,会修改目的buf的写索引。getBytes(...,byte[],...)方法不会修改当前buf读写索引。
@Override public CharSequence readCharSequence(int length, Charset charset) { CharSequence sequence = getCharSequence(readerIndex, length, charset); readerIndex += length; return sequence; } @Override public CharSequence getCharSequence(int index, int length, Charset charset) { // TODO: We could optimize this for UTF8 and US_ASCII return toString(index, length, charset); } @Override public String toString(Charset charset) { return toString(readerIndex, readableBytes(), charset); } @Override public String toString(int index, int length, Charset charset) { return ByteBufUtil.decodeString(this, index, length, charset); }
//ByteBufUtil
/** * A collection of utility methods that is related with handling {@link ByteBuf}, * such as the generation of hex dump and swapping an integer's byte order. */ public final class ByteBufUtil { //Java nio CharBuffer 线程本地字符buf private static final FastThreadLocal<CharBuffer> CHAR_BUFFERS = new FastThreadLocal<CharBuffer>() { @Override protected CharBuffer initialValue() throws Exception { return CharBuffer.allocate(1024); } }; //根据字符编码解析字节buf为字符串 static String decodeString(ByteBuf src, int readerIndex, int len, Charset charset) { if (len == 0) { return StringUtil.EMPTY_STRING; } //获取字符编码 final CharsetDecoder decoder = CharsetUtil.decoder(charset); final int maxLength = (int) ((double) len * decoder.maxCharsPerByte()); //获取线程本地字符buf CharBuffer dst = CHAR_BUFFERS.get(); if (dst.length() < maxLength) { //重新分配maxLength长度的字符buf dst = CharBuffer.allocate(maxLength); if (maxLength <= MAX_CHAR_BUFFER_SIZE) { //添加buf到线程本地字符buf缓存 CHAR_BUFFERS.set(dst); } } else { //清除线程本地字符buf dst.clear(); } if (src.nioBufferCount() == 1) { // Use internalNioBuffer(...) to reduce object creation. //使用源字节buf的内部nio 字节buf,解码数据 decodeString(decoder, src.internalNioBuffer(readerIndex, len), dst); } else { // We use a heap buffer as CharsetDecoder is most likely able to use a fast-path if src and dst buffers // are both backed by a byte array. //否则分配一个堆buf ByteBuf buffer = src.alloc().heapBuffer(len); try { //将源buf数据写到,写到新的堆buf中 buffer.writeBytes(src, readerIndex, len); // Use internalNioBuffer(...) to reduce object creation. //使用buf的内部nio 字节buf,解码数据 decodeString(decoder, buffer.internalNioBuffer(buffer.readerIndex(), len), dst); } finally { // Release the temporary buffer again. 释放buf buffer.release(); } } //返回解码结果 return dst.flip().toString(); } //根据字符解码器器,解码nio字节buf数据到字符buf private static void decodeString(CharsetDecoder decoder, ByteBuffer src, CharBuffer dst) { try { //委托给字符解码器 CoderResult cr = decoder.decode(src, dst, true); if (!cr.isUnderflow()) { cr.throwException(); } //将解码后的数据写到目的字符buf中 cr = decoder.flush(dst); if (!cr.isUnderflow()) { cr.throwException(); } } catch (CharacterCodingException x) { throw new IllegalStateException(x); } } }
回到抽象字节buf,来看set方法:
@Override public ByteBuf setByte(int index, int value) { checkIndex(index); _setByte(index, value); return this; } //待子类扩展 protected abstract void _setByte(int index, int value); @Override public ByteBuf setInt(int index, int value) { checkIndex(index, 4); _setInt(index, value); return this; } //待子类扩展 protected abstract void _setInt(int index, int value);
其他set原始类型方法,思路基本相同。
再来看setBytes(*)系列方法:
@Override public ByteBuf setBytes(int index, ByteBuf src) { setBytes(index, src, src.readableBytes()); return this; } @Override public ByteBuf setBytes(int index, ByteBuf src, int length) { checkIndex(index, length); if (src == null) { throw new NullPointerException("src"); } if (length > src.readableBytes()) { throw new IndexOutOfBoundsException(String.format( "length(%d) exceeds src.readableBytes(%d) where src is: %s", length, src.readableBytes(), src)); } setBytes(index, src, src.readerIndex(), length); //更新源字节buf的读索引 src.readerIndex(src.readerIndex() + length); return this; } @Override public ByteBuf setBytes(int index, byte[] src) { setBytes(index, src, 0, src.length); return this; }
//ByteBuf
public abstract ByteBuf setBytes(int index, byte[] src, int srcIndex, int length); public abstract ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length);
从上面可以看出,setBytes(...,ByteBuf,...)方法不会修改当前buf读写索引,会修改源buf的读索引。setBytes(...,byte[],...)方法不会修改当前buf读写索引。
来set写字符序列
@Override public int setCharSequence(int index, CharSequence sequence, Charset charset) { if (charset.equals(CharsetUtil.UTF_8)) { //确保有足有容量可写 ensureWritable(ByteBufUtil.utf8MaxBytes(sequence)); return ByteBufUtil.writeUtf8(this, index, sequence, sequence.length()); } if (charset.equals(CharsetUtil.US_ASCII)) { //ASCII编码,长度为字符序列长度 int len = sequence.length(); ensureWritable(len); return ByteBufUtil.writeAscii(this, index, sequence, len); } //获取字符序列,charset编码对应的字节数组 byte[] bytes = sequence.toString().getBytes(charset); //确保buf容量足够 ensureWritable(bytes.length); //委托给setBytes setBytes(index, bytes); return bytes.length; }
//ByteBufUtil
/** * Returns max bytes length of UTF8 character sequence. 返回字符系列UTF-8编码的长度 */ public static int utf8MaxBytes(CharSequence seq) { return seq.length() * MAX_BYTES_PER_CHAR_UTF8; } // Fast-Path implementation static int writeUtf8(AbstractByteBuf buffer, int writerIndex, CharSequence seq, int len) { int oldWriterIndex = writerIndex; // We can use the _set methods as these not need to do any index checks and reference checks. // This is possible as we called ensureWritable(...) before. for (int i = 0; i < len; i++) { //遍历字符序列,将字符编码成UTF-8字节,写入字节buf中 char c = seq.charAt(i); if (c < 0x80) { buffer._setByte(writerIndex++, (byte) c); } else if (c < 0x800) { buffer._setByte(writerIndex++, (byte) (0xc0 | (c >> 6))); buffer._setByte(writerIndex++, (byte) (0x80 | (c & 0x3f))); } else if (isSurrogate(c)) { if (!Character.isHighSurrogate(c)) { buffer._setByte(writerIndex++, WRITE_UTF_UNKNOWN); continue; } final char c2; try { // Surrogate Pair consumes 2 characters. Optimistically try to get the next character to avoid // duplicate bounds checking with charAt. If an IndexOutOfBoundsException is thrown we will // re-throw a more informative exception describing the problem. c2 = seq.charAt(++i); } catch (IndexOutOfBoundsException e) { buffer._setByte(writerIndex++, WRITE_UTF_UNKNOWN); break; } if (!Character.isLowSurrogate(c2)) { buffer._setByte(writerIndex++, WRITE_UTF_UNKNOWN); buffer._setByte(writerIndex++, Character.isHighSurrogate(c2) ? WRITE_UTF_UNKNOWN : c2); continue; } int codePoint = Character.toCodePoint(c, c2); // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630. buffer._setByte(writerIndex++, (byte) (0xf0 | (codePoint >> 18))); buffer._setByte(writerIndex++, (byte) (0x80 | ((codePoint >> 12) & 0x3f))); buffer._setByte(writerIndex++, (byte) (0x80 | ((codePoint >> 6) & 0x3f))); buffer._setByte(writerIndex++, (byte) (0x80 | (codePoint & 0x3f))); } else { buffer._setByte(writerIndex++, (byte) (0xe0 | (c >> 12))); buffer._setByte(writerIndex++, (byte) (0x80 | ((c >> 6) & 0x3f))); buffer._setByte(writerIndex++, (byte) (0x80 | (c & 0x3f))); } } return writerIndex - oldWriterIndex; } // Fast-Path implementation static int writeAscii(AbstractByteBuf buffer, int writerIndex, CharSequence seq, int len) { // We can use the _set methods as these not need to do any index checks and reference checks. // This is possible as we called ensureWritable(...) before. for (int i = 0; i < len; i++) { buffer._setByte(writerIndex++, (byte) seq.charAt(i)); } return len; }
回到抽象字节buf,来看read*相关方法:
先来看读一个字节数据
@Override public byte readByte() { //检查是否有1个可读字节数据 checkReadableBytes0(1); int i = readerIndex; //获取读索引对应的字节 byte b = _getByte(i); //更新读索引 readerIndex = i + 1; return b; } //检查是否有minimumReadableBytes个可读字节数据 private void checkReadableBytes0(int minimumReadableBytes) { ensureAccessible(); if (readerIndex > writerIndex - minimumReadableBytes) { throw new IndexOutOfBoundsException(String.format( "readerIndex(%d) + length(%d) exceeds writerIndex(%d): %s", readerIndex, minimumReadableBytes, writerIndex, this)); } } @Override public int readInt() { //读一个int值,所以检查是否有4个可读字节数据 checkReadableBytes0(4); //委托给_getInt int v = _getInt(readerIndex); readerIndex += 4; return v; }
其他get*原始类型方法,思路基本相同
来看readBytes(*)相关方法:
//读取当前buf数据,写到字节数组中 @Override public ByteBuf readBytes(byte[] dst) { readBytes(dst, 0, dst.length); return this; } @Override public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { checkReadableBytes(length); //委托getBytes getBytes(readerIndex, dst, dstIndex, length); readerIndex += length;//更新读索引 return this; }
从上面来看readBytes(byte[],...),会修改当前buf的读索引
@Override public ByteBuf readBytes(ByteBuf dst) { readBytes(dst, dst.writableBytes()); return this; } //读当前buf数据,写到目的字节buf中 @Override public ByteBuf readBytes(ByteBuf dst, int length) { if (length > dst.writableBytes()) { throw new IndexOutOfBoundsException(String.format( "length(%d) exceeds dst.writableBytes(%d) where dst is: %s", length, dst.writableBytes(), dst)); } readBytes(dst, dst.writerIndex(), length); dst.writerIndex(dst.writerIndex() + length);//更新目的buf的写索引 return this; } @Override public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { checkReadableBytes(length); getBytes(readerIndex, dst, dstIndex, length);//更新目的buf的写索引 readerIndex += length;//更新读索引 return this; }
//读当前buf数据到nio 字节buf @Override public ByteBuf readBytes(ByteBuffer dst) { int length = dst.remaining(); checkReadableBytes(length); getBytes(readerIndex, dst); readerIndex += length; return this; }
//ByteBuf
public abstract ByteBuf getBytes(int index, ByteBuffer dst);
//读当前buf数据到GatheringByteChannel @Override public int readBytes(GatheringByteChannel out, int length) throws IOException { checkReadableBytes(length); int readBytes = getBytes(readerIndex, out, length); readerIndex += readBytes; return readBytes; }
//ByteBuf
public abstract int getBytes(int index, GatheringByteChannel out, int length) throws IOException;
//读当前buf数据到FileChannel @Override public int readBytes(FileChannel out, long position, int length) throws IOException { checkReadableBytes(length); int readBytes = getBytes(readerIndex, out, position, length); readerIndex += readBytes; return readBytes; }
//ByteBuf
public abstract int getBytes(int index, FileChannel out, long position, int length) throws IOException
//读当前buf数据到OutputStream @Override public ByteBuf readBytes(OutputStream out, int length) throws IOException { checkReadableBytes(length); getBytes(readerIndex, out, length); readerIndex += length; return this; }
//ByteBuf
public abstract ByteBuf getBytes(int index, OutputStream out, int length) throws IOException;
从上面可以看出,read*原始类型方法会修改当前buf读索引,readBytes(...,ByteBuf,...)方法会修改当前buf读索引,同时会修改目的buf的写索引,readBytes(...,byte[],...)方法会修改当前buf读索引。read*操作实际委托个get*的相关操作,同时更新buf读索引。
再来看readSlice相关方法
@Override public ByteBuf readSlice(int length) { ByteBuf slice = slice(readerIndex, length); readerIndex += length; return slice; } @Override public ByteBuf readRetainedSlice(int length) { ByteBuf slice = retainedSlice(readerIndex, length); readerIndex += length; return slice; } @Override public ByteBuf slice(int index, int length) { return new UnpooledSlicedByteBuf(this, index, length); } @Override public ByteBuf retainedSlice(int index, int length) { return slice(index, length).retain(); }
//UnpooledSlicedByteBuf
class UnpooledSlicedByteBuf extends AbstractUnpooledSlicedByteBuf { UnpooledSlicedByteBuf(AbstractByteBuf buffer, int index, int length) { super(buffer, index, length); @Override public AbstractByteBuf unwrap() { return (AbstractByteBuf) super.unwrap(); } @Override protected byte _getByte(int index) { return unwrap()._getByte(idx(index)); } //其他get方法思路基本相同 ... }
//AbstractUnpooledSlicedByteBuf,可以理解为字节buf的静态代理
abstract class AbstractUnpooledSlicedByteBuf extends AbstractDerivedByteBuf { private final ByteBuf buffer;//内部字节buf private final int adjustment; //获取内部字节buf @Override public ByteBuf unwrap() { return buffer; } @Override public byte getByte(int index) { checkIndex0(index, 1); return unwrap().getByte(idx(index)); } @Override protected byte _getByte(int index) { return unwrap().getByte(idx(index)); } //其他字节buf的相关方法,都是委托给内部字节buf ... }
//AbstractDerivedByteBuf,可以理解实现了引用计数器的抽象字节buf
public abstract class AbstractDerivedByteBuf extends AbstractByteBuf { protected AbstractDerivedByteBuf(int maxCapacity) { super(maxCapacity); } @Override public final int refCnt() { return refCnt0(); } int refCnt0() { return unwrap().refCnt(); } @Override public final ByteBuf retain() { return retain0(); } ByteBuf retain0() { unwrap().retain(); return this; } ... }
//ByteBuf
/** * Return the underlying buffer instance if this buffer is a wrapper of another buffer. * * @return {@code null} if this buffer is not a wrapper */ public abstract ByteBuf unwrap();
从上面可以看出retainedSlice和slice方法返回则的字节buf,实际为字节buf底层unwrap buf,
可以理解为字节buf的快照或引用,数据更改相互影响,retainedSlice方法会增加字节buf的引用计数器。
再来看读部分数据到字节序列
@Override public CharSequence readCharSequence(int length, Charset charset) { CharSequence sequence = getCharSequence(readerIndex, length, charset); readerIndex += length; return sequence; }
再来看skipBytes方法
//跳过length长度的字节,只更新读索引,不删除实际buf数据 @Override public ByteBuf skipBytes(int length) { checkReadableBytes(length); readerIndex += length; return this; }
再来看write*相关方法:
@Override public ByteBuf writeByte(int value) { ensureAccessible(); //确保buf,足够容下1个字节数据 ensureWritable0(1); //委托给_setByte,并更新写索引 _setByte(writerIndex++, value); return this; } //确保buf,足够容下minWritableBytes个字节数据 @Override public ByteBuf ensureWritable(int minWritableBytes) { if (minWritableBytes < 0) { throw new IllegalArgumentException(String.format( "minWritableBytes: %d (expected: >= 0)", minWritableBytes)); } ensureWritable0(minWritableBytes); return this; } private void ensureWritable0(int minWritableBytes) { if (minWritableBytes <= writableBytes()) { return; } if (minWritableBytes > maxCapacity - writerIndex) { throw new IndexOutOfBoundsException(String.format( "writerIndex(%d) + minWritableBytes(%d) exceeds maxCapacity(%d): %s", writerIndex, minWritableBytes, maxCapacity, this)); } // Normalize the current capacity to the power of 2. 计算新的buf容量 int newCapacity = alloc().calculateNewCapacity(writerIndex + minWritableBytes, maxCapacity); // Adjust to the new capacity. //调整容量 capacity(newCapacity); } @Override public int ensureWritable(int minWritableBytes, boolean force) { if (minWritableBytes < 0) { throw new IllegalArgumentException(String.format( "minWritableBytes: %d (expected: >= 0)", minWritableBytes)); } if (minWritableBytes <= writableBytes()) { //不够写 return 0; } final int maxCapacity = maxCapacity(); final int writerIndex = writerIndex(); if (minWritableBytes > maxCapacity - writerIndex) { if (!force || capacity() == maxCapacity) { return 1; } //扩展至最大容量 capacity(maxCapacity); return 3; } //计算新的容量,并更新 // Normalize the current capacity to the power of 2. int newCapacity = alloc().calculateNewCapacity(writerIndex + minWritableBytes, maxCapacity); // Adjust to the new capacity. capacity(newCapacity); return 2; }
再来看写int
@Override public ByteBuf writeInt(int value) { ensureAccessible(); //确保buf,足够容下4个字节数据 ensureWritable0(4); _setInt(writerIndex, value); writerIndex += 4;//更新写索引 return this; }
其他write*原始类型方法,思路基本相同;
再来看writeBytes相关方法
将字节数组数据写到当前buf
@Override public ByteBuf writeBytes(byte[] src) { writeBytes(src, 0, src.length); return this; } @Override public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { ensureAccessible(); ensureWritable(length); setBytes(writerIndex, src, srcIndex, length); writerIndex += length; return this; }
将字节buf数据写到当前buf
@Override public ByteBuf writeBytes(ByteBuf src) { writeBytes(src, src.readableBytes()); return this; } @Override public ByteBuf writeBytes(ByteBuf src, int length) { if (length > src.readableBytes()) { throw new IndexOutOfBoundsException(String.format( "length(%d) exceeds src.readableBytes(%d) where src is: %s", length, src.readableBytes(), src)); } writeBytes(src, src.readerIndex(), length); src.readerIndex(src.readerIndex() + length); return this; } @Override public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { ensureAccessible(); ensureWritable(length); setBytes(writerIndex, src, srcIndex, length); writerIndex += length; return this; }
再来看将nio 字节buf,InputStream,ScatteringByteChannel,FileChannel中的数据写到
当前buf
@Override public ByteBuf writeBytes(ByteBuffer src) { ensureAccessible(); int length = src.remaining(); ensureWritable(length); setBytes(writerIndex, src); writerIndex += length; return this; }
//ByteBuf
public abstract ByteBuf setBytes(int index, ByteBuffer src);
@Override public int writeBytes(InputStream in, int length) throws IOException { ensureAccessible(); ensureWritable(length); int writtenBytes = setBytes(writerIndex, in, length); if (writtenBytes > 0) { writerIndex += writtenBytes; } return writtenBytes; }
//ByteBuf
public abstract int setBytes(int index, InputStream in, int length) throws IOException;
@Override public int writeBytes(ScatteringByteChannel in, int length) throws IOException { ensureAccessible(); ensureWritable(length); int writtenBytes = setBytes(writerIndex, in, length); if (writtenBytes > 0) { writerIndex += writtenBytes; } return writtenBytes; }
//ByteBuf
public abstract int setBytes(int index, ScatteringByteChannel in, int length) throws IOException;
@Override public int writeBytes(FileChannel in, long position, int length) throws IOException { ensureAccessible(); ensureWritable(length); int writtenBytes = setBytes(writerIndex, in, position, length); if (writtenBytes > 0) { writerIndex += writtenBytes; } return writtenBytes; }
//ByteBuf
public abstract int setBytes(int index, FileChannel in, long position, int length) throws IOException;
//写字节序列 @Override public int writeCharSequence(CharSequence sequence, Charset charset) { int written = setCharSequence(writerIndex, sequence, charset); writerIndex += written; return written; }
从上面可以看出write*原始类型方法会修改当前buf写索引,writeBytes(...,ByteBuf,...)方法会修改当前buf写索引,同时会修改目的buf的读索引,writeBytes(...,byte[],...)方法会修改当前buf写索引。write*操作实际委托个set*的相关操作,同时更新buf写索引。
再来看复制方法:
@Override public ByteBuf copy() { return copy(readerIndex, readableBytes()); }
//ByteBuf
public abstract ByteBuf copy(int index, int length);
slice和retainedSlice相关的方法,我们在前面已说,这里仅仅展示一下:
@Override public ByteBuf slice() { return slice(readerIndex, readableBytes()); } @Override public ByteBuf retainedSlice() { return slice().retain(); } @Override public ByteBuf slice(int index, int length) { return new UnpooledSlicedByteBuf(this, index, length); } @Override public ByteBuf retainedSlice(int index, int length) { return slice(index, length).retain(); }
来看完全复制duplicate
@Override public ByteBuf duplicate() { return new UnpooledDuplicatedByteBuf(this); }@Override public ByteBuf retainedDuplicate() { return duplicate().retain(); }
//UnpooledDuplicatedByteBuf
class UnpooledDuplicatedByteBuf extends DuplicatedByteBuf {
UnpooledDuplicatedByteBuf(AbstractByteBuf buffer) {
super(buffer);
}
@Override
public AbstractByteBuf unwrap() {
return (AbstractByteBuf) super.unwrap();
}
@Override
protected byte _getByte(int index) {
return unwrap()._getByte(index);
}
//其他方法思路一样委托给内存的buf
...
}
//可以理解为buf的静态代理
@Deprecated public class DuplicatedByteBuf extends AbstractDerivedByteBuf { private final ByteBuf buffer; public DuplicatedByteBuf(ByteBuf buffer) { this(buffer, buffer.readerIndex(), buffer.writerIndex()); } @Override public byte getByte(int index) { return unwrap().getByte(index); } 其他方法思路一样委托给内存的buf ... }
从上面可以看出:retainedDuplicate和duplicate方法返回则的字节buf,实际为字节buf底层unwrap buf,可以理解为字节buf的快照或引用,数据更改相互影响,retainedDuplicate方法会增加字节buf的引用计数器。
再来看转化nio ByteBuffer
@Override public ByteBuffer nioBuffer() { return nioBuffer(readerIndex, readableBytes()); } @Override public ByteBuffer[] nioBuffers() { return nioBuffers(readerIndex, readableBytes()); }
//ByteBuf
public abstract ByteBuffer[] nioBuffers(int index, int length);
总结:
字节buf内部有两个索引,一个读索引,一个写索引,两个索引标记,即读写索引对应的标记,buf的最大容量为maxCapacity;buf的构造,主要是初始化最大容量。
弃已读数据方法discardReadBytes,丢弃buf数据时,只修改读写索引和相应的标记,并不删除数据。
get*原始类型方法不会修改当前buf读写索引,getBytes(...,ByteBuf,...)方法不会修改当前buf读写索引,会修改目的buf的写索引。getBytes(...,byte[],...)方法不会修改当前buf读写索引。
set*原始类型方法不会修改当前buf读写索引,setBytes(...,ByteBuf,...)方法不会修改当前buf读写索引,会修改源buf的读索引。setBytes(...,byte[],...)方法不会修改当前buf读写索引。
read*原始类型方法会修改当前buf读索引,readBytes(...,ByteBuf,...)方法会修改当前buf读索引,同时会修改目的buf的写索引,readBytes(...,byte[],...)方法会修改当前buf读索引。
read*操作实际委托个get*的相关操作,同时更新buf读索引。
跳过length长度的字节,只更新读索引,不删除实际buf数据。
retainedSlice和slice方法返回则的字节buf,实际为字节buf底层unwrap buf,可以理解为字节buf的快照或引用,数据更改相互影响,retainedSlice方法会增加字节buf的引用计数器。
write*原始类型方法会修改当前buf写索引,writeBytes(...,ByteBuf,...)方法会修改当前buf写索引,同时会修改目的buf的读索引,readBytes(...,byte[],...)方法会修改当前buf写索引。
write*操作实际委托个set*的相关操作,同时更新buf写索引。
retainedDuplicate和duplicate方法返回则的字节buf,实际为字节buf底层unwrap buf,可以理解为字节buf的快照或引用,数据更改相互影响,retainedDuplicate方法会增加字节buf的引用计数器。
附:
//字节查找 @Override public int indexOf(int fromIndex, int toIndex, byte value) { return ByteBufUtil.indexOf(this, fromIndex, toIndex, value); }
//ByteBufUtil
/
** * The default implementation of {@link ByteBuf#indexOf(int, int, byte)}. * This method is useful when implementing a new buffer type. */ public static int indexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { if (fromIndex <= toIndex) { return firstIndexOf(buffer, fromIndex, toIndex, value); } else { return lastIndexOf(buffer, fromIndex, toIndex, value); } } private static int firstIndexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { fromIndex = Math.max(fromIndex, 0); if (fromIndex >= toIndex || buffer.capacity() == 0) { return -1; } return buffer.forEachByte(fromIndex, toIndex - fromIndex, new ByteProcessor.IndexOfProcessor(value)); } private static int lastIndexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { fromIndex = Math.min(fromIndex, buffer.capacity()); if (fromIndex < 0 || buffer.capacity() == 0) { return -1; } return buffer.forEachByteDesc(toIndex, fromIndex - toIndex, new ByteProcessor.IndexOfProcessor(value)); }
//ByteProcessor
public interface ByteProcessor { /** * A {@link ByteProcessor} which finds the first appearance of a specific byte. */ class IndexOfProcessor implements ByteProcessor { private final byte byteToFind; public IndexOfProcessor(byte byteToFind) { this.byteToFind = byteToFind; } @Override public boolean process(byte value) { return value != byteToFind; } } ... }
//获取字节在buf中的第一个索引位置与开始索引之前的长度 @Override public int bytesBefore(byte value) { return bytesBefore(readerIndex(), readableBytes(), value); } @Override public int bytesBefore(int length, byte value) { checkReadableBytes(length); return bytesBefore(readerIndex(), length, value); } @Override public int bytesBefore(int index, int length, byte value) { //委托给indexOf int endIndex = indexOf(index, index + length, value); if (endIndex < 0) { return -1; } return endIndex - index; }
//遍历buf所有字节,调用处理器,处理
升序方式
@Override public int forEachByte(ByteProcessor processor) { ensureAccessible(); try { return forEachByteAsc0(readerIndex, writerIndex, processor); } catch (Exception e) { PlatformDependent.throwException(e); return -1; } } @Override public int forEachByte(int index, int length, ByteProcessor processor) { checkIndex(index, length); try { return forEachByteAsc0(index, index + length, processor); } catch (Exception e) { PlatformDependent.throwException(e); return -1; } } private int forEachByteAsc0(int start, int end, ByteProcessor processor) throws Exception { for (; start < end; ++start) { if (!processor.process(_getByte(start))) { return start; } } return -1; }
倒序方式
@Override public int forEachByteDesc(ByteProcessor processor) { ensureAccessible(); try { return forEachByteDesc0(writerIndex - 1, readerIndex, processor); } catch (Exception e) { PlatformDependent.throwException(e); return -1; } } @Override public int forEachByteDesc(int index, int length, ByteProcessor processor) { checkIndex(index, length); try { return forEachByteDesc0(index + length - 1, index, processor); } catch (Exception e) { PlatformDependent.throwException(e); return -1; } } private int forEachByteDesc0(int rStart, final int rEnd, ByteProcessor processor) throws Exception { for (; rStart >= rEnd; --rStart) { if (!processor.process(_getByte(rStart))) { return rStart; } } return -1; }
@Override public int hashCode() { return ByteBufUtil.hashCode(this); } @Override public boolean equals(Object o) { return this == o || (o instanceof ByteBuf && ByteBufUtil.equals(this, (ByteBuf) o)); } @Override public int compareTo(ByteBuf that) { return ByteBufUtil.compare(this, that); } @Override public String toString() { if (refCnt() == 0) { return StringUtil.simpleClassName(this) + "(freed)"; } StringBuilder buf = new StringBuilder() .append(StringUtil.simpleClassName(this)) .append("(ridx: ").append(readerIndex) .append(", widx: ").append(writerIndex) .append(", cap: ").append(capacity()); if (maxCapacity != Integer.MAX_VALUE) { buf.append('/').append(maxCapacity); } ByteBuf unwrapped = unwrap(); if (unwrapped != null) { buf.append(", unwrapped: ").append(unwrapped); } buf.append(')'); return buf.toString(); }
发表评论
-
netty NioSocketChannel解析
2017-09-29 12:50 1368netty 抽象BootStrap定义:http://dona ... -
netty Pooled字节buf分配器
2017-09-28 13:00 2099netty 字节buf定义:http://donald-dra ... -
netty Unpooled字节buf分配器
2017-09-26 22:01 2501netty 字节buf定义:http://donald-dra ... -
netty 抽象字节buf分配器
2017-09-26 08:43 1347netty 字节buf定义:http:// ... -
netty 复合buf概念
2017-09-25 22:31 1347netty 字节buf定义:http://donald-dra ... -
netty 抽象字节buf引用计数器
2017-09-22 12:48 1627netty 字节buf定义:http://donald-dra ... -
netty 资源泄漏探测器
2017-09-21 09:37 1440netty 通道接口定义:http://donald-drap ... -
netty 字节buf定义
2017-09-20 08:31 2880netty 通道接口定义:http://donald-drap ... -
netty 默认通道配置后续
2017-09-18 08:36 2225netty 通道接口定义:http://donald-drap ... -
netty 默认通道配置初始化
2017-09-17 22:51 2069netty 通道接口定义:http://donald-drap ... -
netty 通道配置接口定义
2017-09-17 14:51 1118netty 通道接口定义:http://donald-drap ... -
netty NioServerSocketChannel解析
2017-09-16 13:01 1910netty ServerBootStrap解析:http:// ... -
netty 抽象nio消息通道
2017-09-15 15:30 1257netty 通道接口定义:http:/ ... -
netty 抽象nio字节通道
2017-09-14 22:39 1243netty 通道接口定义:http:/ ... -
netty 抽象nio通道解析
2017-09-14 17:23 992netty 通道接口定义:http://donald-drap ... -
netty 抽象通道后续
2017-09-13 22:40 1335netty Inboudn/Outbound通道Inv ... -
netty 通道Outbound缓冲区
2017-09-13 14:31 2221netty 通道接口定义:http:/ ... -
netty 抽象Unsafe定义
2017-09-12 21:24 1137netty 通道接口定义:http:/ ... -
netty 抽象通道初始化
2017-09-11 12:56 1897netty 管道线定义-ChannelPipeline:htt ... -
netty 通道接口定义
2017-09-10 15:36 1928netty Inboudn/Outbound通道Invoker ...
相关推荐
#### Buf 的 Unpooled 实现 **1. UnpooledHeapByteBuf** `UnpooledHeapByteBuf`是在堆上创建的`ByteBuf`实现。它是非线程安全的,并且没有使用任何额外的内存管理机制。这种实现简单且易于理解,适用于那些不需要...
拟阵约束下最大化子模函数的模型及其算法的一种熵聚类方法.pdf
内容概要:本文探讨了在两级电力市场环境中,针对省间交易商的最优购电模型的研究。文中提出了一个双层非线性优化模型,用于处理省内电力市场和省间电力交易的出清问题。该模型采用CVaR(条件风险价值)方法来评估和管理由新能源和负荷不确定性带来的风险。通过KKT条件和对偶理论,将复杂的双层非线性问题转化为更易求解的线性单层问题。此外,还通过实际案例验证了模型的有效性,展示了不同风险偏好设置对购电策略的影响。 适合人群:从事电力系统规划、运营以及风险管理的专业人士,尤其是对电力市场机制感兴趣的学者和技术专家。 使用场景及目标:适用于希望深入了解电力市场运作机制及其风险控制手段的研究人员和技术开发者。主要目标是为省间交易商提供一种科学有效的购电策略,以降低风险并提高经济效益。 其他说明:文章不仅介绍了理论模型的构建过程,还包括具体的数学公式推导和Python代码示例,便于读者理解和实践。同时强调了模型在实际应用中存在的挑战,如数据精度等问题,并指出了未来改进的方向。
内容概要:本文探讨了在MATLAB/Simulink平台上针对四机两区系统的风储联合调频技术。首先介绍了四机两区系统作为经典的电力系统模型,在风电渗透率增加的情况下,传统一次调频方式面临挑战。接着阐述了风储联合调频技术的应用,通过引入虚拟惯性控制和下垂控制策略,提高了系统的频率稳定性。文章展示了具体的MATLAB/Simulink仿真模型,包括系统参数设置、控制算法实现以及仿真加速方法。最终结果显示,在风电渗透率为25%的情况下,通过风储联合调频,系统频率特性得到显著提升,仿真时间缩短至5秒以内。 适合人群:从事电力系统研究、仿真建模的技术人员,特别是关注风电接入电网稳定性的研究人员。 使用场景及目标:适用于希望深入了解风储联合调频机制及其仿真实现的研究人员和技术开发者。目标是掌握如何利用MATLAB/Simulink进行高效的电力系统仿真,尤其是针对含有高比例风电接入的复杂场景。 其他说明:文中提供的具体参数配置和控制算法有助于读者快速搭建类似的仿真环境,并进行相关研究。同时强调了参考文献对于理论基础建立的重要性。
内容概要:本文介绍了永磁同步电机(PMSM)无感控制技术,特别是高频方波注入与滑膜观测器相结合的方法。首先解释了高频方波注入法的工作原理,即通过向电机注入高频方波电压信号,利用电机的凸极效应获取转子位置信息。接着讨论了滑膜观测器的作用,它能够根据电机的电压和电流估计转速和位置,具有较强的鲁棒性。两者结合可以提高无传感器控制系统的稳定性和精度。文中还提供了具体的Python、C语言和Matlab代码示例,展示了如何实现这两种技术。此外,简要提及了正弦波注入的相关论文资料,强调了其在不同工况下的优势。 适合人群:从事电机控制系统设计的研发工程师和技术爱好者,尤其是对永磁同步电机无感控制感兴趣的读者。 使用场景及目标:适用于需要减少传感器依赖、降低成本并提高系统可靠性的情况,如工业自动化设备、电动汽车等领域的电机控制。目标是掌握高频方波注入与滑膜观测器结合的具体实现方法,应用于实际工程项目中。 其他说明:文中提到的高频方波注入和滑膜观测器的结合方式,不仅提高了系统的性能,还在某些特殊情况下表现出更好的适应性。同时,附带提供的代码片段有助于读者更好地理解和实践这一技术。
内容概要:本文深入探讨了MATLAB中扩展卡尔曼滤波(EKF)和双扩展卡尔曼滤波(DEKF)在电池参数辨识中的应用。首先介绍了EKF的基本原理和代码实现,包括状态预测和更新步骤。接着讨论了DEKF的工作机制,即同时估计系统状态和参数,解决了参数和状态耦合估计的问题。文章还详细描述了电池参数辨识的具体应用场景,特别是针对电池管理系统中的荷电状态(SOC)估计。此外,提到了一些实用技巧,如雅可比矩阵的计算、参数初始值的选择、数据预处理方法等,并引用了几篇重要文献作为参考。 适合人群:从事电池管理系统开发的研究人员和技术人员,尤其是对状态估计和参数辨识感兴趣的读者。 使用场景及目标:适用于需要精确估计电池参数的实际项目,如电动汽车、储能系统等领域。目标是提高电池管理系统的性能,确保电池的安全性和可靠性。 其他说明:文章强调了实际应用中的注意事项,如数据处理、参数选择和模型优化等方面的经验分享。同时提醒读者关注最新的研究成果和技术进展,以便更好地应用于实际工作中。
内容概要:本文详细介绍了在无电子凸轮功能情况下,利用三菱FX3U系列PLC和威纶通触摸屏实现分切机上下收放卷张力控制的方法。主要内容涵盖硬件连接、程序框架设计、张力检测与读取、PID控制逻辑以及触摸屏交互界面的设计。文中通过具体代码示例展示了如何初始化寄存器、读取张力传感器数据、计算张力偏差并实施PID控制,最终实现稳定的张力控制。此外,还讨论了卷径计算、速度同步控制等关键技术点,并提供了现场调试经验和优化建议。 适合人群:从事自动化生产设备维护和技术支持的专业人士,尤其是熟悉PLC编程和触摸屏应用的技术人员。 使用场景及目标:适用于需要对分切机进行升级改造的企业,旨在提高分切机的张力控制精度,确保材料切割质量,降低生产成本。通过本方案可以实现±3%的张力控制精度,满足基本生产需求。 其他说明:本文不仅提供详细的程序代码和硬件配置指南,还分享了许多实用的调试技巧和经验,帮助技术人员更好地理解和应用相关技术。
内容概要:本文详细介绍了一种基于西门子S7-200和S7-300 PLC以及组态王软件的三泵变频恒压供水系统。主要内容涵盖IO分配、接线图原理图、梯形图程序编写和组态画面设计四个方面。通过合理的硬件配置和精确的编程逻辑,确保系统能够在不同负载情况下保持稳定的供水压力,同时实现节能和延长设备使用寿命的目标。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是熟悉PLC编程和组态软件使用的专业人士。 使用场景及目标:适用于需要稳定供水的各种场合,如住宅小区、工厂等。目标是通过优化控制系统,提升供水效率,减少能源消耗,并确保系统的可靠性和安全性。 其他说明:文中提供了详细的实例代码和调试技巧,帮助读者更好地理解和实施该项目。此外,还分享了一些实用的经验教训,有助于避免常见的错误和陷阱。
内容概要:本文详细介绍了三相三线制静止无功发生器(SVG/STATCOM)在Simulink中的仿真模型设计与实现。主要内容涵盖ip-iq检测法用于无功功率检测、dq坐标系下的电流解耦控制、电压电流双闭环控制系统的设计、SVPWM调制技术的应用以及具体的仿真参数设置。文中不仅提供了理论背景,还展示了具体的Matlab代码片段,帮助读者理解各个控制环节的工作原理和技术细节。此外,文章还讨论了实际调试中遇到的问题及解决方案,强调了参数调整的重要性。 适合人群:从事电力系统自动化、电力电子技术研究的专业人士,特别是对SVG/STATCOM仿真感兴趣的工程师和研究人员。 使用场景及目标:适用于希望深入了解SVG/STATCOM工作原理并掌握其仿真方法的研究人员和工程师。目标是在实践中能够正确搭建和优化SVG/STATCOM的仿真模型,提高无功补偿的效果。 其他说明:文章提供了丰富的实例代码和调试技巧,有助于读者更好地理解和应用所学知识。同时,文中提及的一些经验和注意事项来源于实际项目,具有较高的参考价值。
基于SIMULINK的风力机发电效率建模探究.pdf
内容概要:本文介绍了如何将CarSim的动力学模型与Simulink的智能算法相结合,利用模型预测控制(MPC)实现车辆的智能超车换道。主要内容包括MPC控制器的设计、路径规划算法、联合仿真的配置要点以及实际应用效果。文中提供了详细的代码片段和技术细节,如权重矩阵设置、路径跟踪目标函数、安全超车条件判断等。此外,还强调了仿真过程中需要注意的关键参数配置,如仿真步长、插值设置等,以确保系统的稳定性和准确性。 适合人群:从事自动驾驶研究的技术人员、汽车工程领域的研究人员、对联合仿真感兴趣的开发者。 使用场景及目标:适用于需要进行自动驾驶车辆行为模拟的研究机构和企业,旨在提高超车换道的安全性和效率,为自动驾驶技术研发提供理论支持和技术验证。 其他说明:随包提供的案例文件已调好所有参数,可以直接导入并运行,帮助用户快速上手。文中提到的具体参数和配置方法对于初学者非常友好,能够显著降低入门门槛。
内容概要:本文详细介绍了利用MATLAB进行信号与系统实验的具体步骤和技术要点。首先讲解了常见信号(如方波、sinc函数、正弦波等)的生成方法及其注意事项,强调了时间轴设置和参数调整的重要性。接着探讨了卷积积分的两种实现方式——符号运算和数值积分,指出了各自的特点和应用场景,并特别提醒了数值卷积时的时间轴重构和步长修正问题。随后深入浅出地解释了频域分析的方法,包括傅里叶变换的符号计算和快速傅里叶变换(FFT),并给出了具体的代码实例和常见错误提示。最后阐述了离散时间信号与系统的Z变换分析,展示了如何通过Z变换将差分方程转化为传递函数以及如何绘制零极点图来评估系统的稳定性。 适合人群:正在学习信号与系统课程的学生,尤其是需要完成相关实验任务的人群;对MATLAB有一定基础,希望通过实践加深对该领域理解的学习者。 使用场景及目标:帮助学生掌握MATLAB环境下信号生成、卷积积分、频域分析和Z变换的基本技能;提高学生解决实际问题的能力,避免常见的编程陷阱;培养学生的动手能力和科学思维习惯。 其他说明:文中不仅提供了详细的代码示例,还分享了许多实用的小技巧,如如何正确保存实验结果图、如何撰写高质量的实验报告等。同时,作者以幽默风趣的语言风格贯穿全文,使得原本枯燥的技术内容变得生动有趣。
KUKA机器人相关文档
内容概要:本文详细介绍了无传感器永磁同步电机(PMSM)控制技术,特别是针对低速和中高速的不同控制策略。低速阶段采用I/F控制,通过固定电流幅值和斜坡加速的方式启动电机,确保平稳启动。中高速阶段则引入滑模观测器进行反电动势估算,从而精确控制电机转速。文中还讨论了两者之间的平滑切换逻辑,强调了参数选择和调试技巧的重要性。此外,提供了具体的伪代码示例,帮助读者更好地理解和实现这一控制方案。 适合人群:从事电机控制系统设计的研发工程师和技术爱好者。 使用场景及目标:适用于需要降低成本并提高可靠性的应用场景,如家用电器、工业自动化设备等。主要目标是掌握无传感器PMSM控制的基本原理及其优化方法。 其他说明:文中提到的实际案例和测试数据有助于加深理解,同时提醒开发者注意硬件参数准确性以及调试过程中可能出现的问题。
智能家居与物联网培训材料.ppt
内容概要:本文详细介绍了使用Matlab解决车辆路径规划问题的四种经典算法:TSP(旅行商问题)、CVRP(带容量约束的车辆路径问题)、CDVRP(带容量和距离双重约束的车辆路径问题)和VRPTW(带时间窗约束的车辆路径问题)。针对每个问题,文中提供了具体的算法实现思路和关键代码片段,如遗传算法用于TSP的基础求解,贪心算法和遗传算法结合用于CVRP的路径分割,以及带有惩罚函数的时间窗约束处理方法。此外,还讨论了性能优化技巧,如矩阵运算替代循环、锦标赛选择、2-opt局部优化等。 适合人群:具有一定编程基础,尤其是对物流调度、路径规划感兴趣的开发者和技术爱好者。 使用场景及目标:适用于物流配送系统的路径优化,旨在提高配送效率,降低成本。具体应用场景包括但不限于外卖配送、快递运输等。目标是帮助读者掌握如何利用Matlab实现高效的路径规划算法,解决实际业务中的复杂约束条件。 其他说明:文中不仅提供了详细的代码实现,还分享了许多实践经验,如参数设置、数据预处理、异常检测等。建议读者在实践中不断尝试不同的算法组合和优化策略,以应对更加复杂的实际问题。
软考网络工程师2010-2014真题及答案完整版 全国计算机软考 适合软考中级人群
包括:源程序工程文件、Proteus仿真工程文件、论文材料、配套技术手册等 1、采用51/52单片机作为主控芯片; 2、采用1602液晶显示:测量酒精值、酒驾阈值、醉驾阈值; 3、采用PCF8591进行AD模数转换; 4、LED指示:正常绿灯、酒驾黄灯、醉驾红灯; 5、可通过按键修改酒驾醉驾阈值;
内容概要:本文详细介绍了利用MATLAB实现约束最优化求解的方法,主要分为两大部分:无约束优化和带约束优化。对于无约束优化,作者首先讲解了梯度下降法的基本原理和实现技巧,如步长搜索和Armijo条件的应用。接着深入探讨了带约束优化问题,特别是序列二次规划(SQP)方法的具体实现,包括拉格朗日函数的Hesse矩阵计算、QP子问题的构建以及拉格朗日乘子的更新策略。文中不仅提供了详细的MATLAB代码示例,还分享了许多调参经验和常见错误的解决办法。 适合人群:具备一定数学基础和编程经验的研究人员、工程师或学生,尤其是对最优化理论和应用感兴趣的读者。 使用场景及目标:适用于需要解决各类优化问题的实际工程项目,如机械臂能耗最小化、化工过程优化等。通过学习本文,读者能够掌握如何将复杂的约束优化问题分解为更易处理的二次规划子问题,从而提高求解效率和准确性。 其他说明:文章强调了优化算法选择的重要性,指出不同的问题结构决定了最适合的算法。此外,作者还分享了一些实用的经验教训,如Hesse矩阵的正定性处理和惩罚因子的动态调整,帮助读者少走弯路。