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.

5.1. The ByteBuf API

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.

5.2. Class ByteBuf—Netty’s data container

5.3. Byte-level operations

5.4. Interface ByteBufHolder

5.5. ByteBuf allocation

5.6. Reference counting

5.7. Summary

sitemap