Chapter 5. ByteBuf
This chapter covers
- ByteBuf —Netty’s data container
- API details
- Use cases
- Memory allocation
As we noted earlier, the fundamental unit of network data is always the byte. Java NIO provides ByteBuffer as its byte container, but this class makes usage overly complex and somewhat cumbersome to use.
Netty’s alternative to ByteBuffer is ByteBuf, a powerful implementation that addresses the limitations of the JDK API and provides a better API for network application developers.
In this chapter we’ll illustrate the superior functionality and flexibility of ByteBuf as compared to the JDK’s ByteBuffer. This will also give you a better understanding of Netty’s approach to data handling in general and prepare you for our discussion of ChannelPipeline and ChannelHandler in chapter 6.
Netty’s API for data handling is exposed through two components—abstract class ByteBuf and interface ByteBufHolder.
These are some of the advantages of the ByteBuf API:
- It’s extensible to user-defined buffer types.
- Transparent zero-copy is achieved by a built-in composite buffer type.
- Capacity is expanded on demand (as with the JDK StringBuilder).
- Switching between reader and writer modes doesn’t require calling ByteBuffer’s flip() method.
- Reading and writing employ distinct indices.
- Method chaining is supported.
- Reference counting is supported.
- Pooling is supported.