What is ByteBuf used for? A container for passing byte data in Netty.
What are the usage patterns for ByteBuf?
Usage patterns | describe | advantages | disadvantage |
---|---|---|---|
Heap buffer | The data store is stored in the JVM’s heap space, also known as the support array, and hasArray is used to determine whether it is in the heap buffer | Provides fast allocation and release without using pooling | It is copied to the direct buffer before sending |
Direct buffer | Stored in physical memory |
|
|
Composite buffer | A single buffer merges multiple buffer representations | Multiple operations are more convenient | – |
How to access ByteBuf?
- Subscript access: get, related methods starting with set, do not modify the index
- Index access: methods beginning with read,write that adjust the index based on the bytes already accessed [indexes are ByteBuf’s built-in readIndex and writeIndex]
ByteBuf has a capacity limit of its own. The default maximum is intege.max_value. IndeOutOfBoundsException is thrown out of range
What about the ByteBuf index operation?
The two indexes separate ByteBuf into three regions
The default size for any newly allocated, wrapped, or copied readerIndex/writeIndex is 0, anything that starts with read or skip increases the read bytes of readerIndex, and anything that starts with write increases the corresponding writeIndex bytes. Other arguments that contain ByteBuf and have no target index, such as readBytes(ByteBuf dest) writeBytes(ByteBuf dest) Dest)], will affect the corresponding readerIndex (write method affects readerIndex) writeIndex (read method affects writeIndex).
DiscardReadBytes () moves the readable byte to subscript 0, shifting the readable byte (the original readable byte is not erased, just the writeIndex is moved)
Calling the clear() method simply resets the index so that readIndex and writeIndex are 0 and no memory copying is done
What is the derived buffer of ByteBuf?
ByteBuf is a method for rendering a view of content that returns a new ByteBuf instance with its own index, but the internal storage is shared, meaning that its content changes as well as the source instance. Methods such as slice/Unpooled unmodifiableBuffer/order/readSlice/duplicate.
Select Copy if you need a fully independent copy
Is there any other way ByteBuf can manage instances?
- ByteBufAllocator: Can get its reference using ChannelHandleContext (channels each have a different instance, or ChannelHandler gets it), Starting from 4.1.x, Netty uses pooledBytefallocator by default to minimize memory fragmentation. Another method is unpooledbytefallocator, which returns a new instance each time.
- Unpooled: a utility class that provides static methods to create an Unpooled ByteBuf
- ByteBufUtil: Implements methods used, such as equals to determine whether two bytebufs are equal, and hexdump to print the contents of ByteBuf in hexadecimal