Netty: Question: Correct way to allocate ByteBuf

Created on 9 Sep 2016  路  4Comments  路  Source: netty/netty

Hi,

Whats the correct way to create / get an new ByteBuf?

Currently i use Unpooled.buffer().

ByteBuf content = Unpooled.buffer();

Is there an better way? Maybe using pooled buffers?
Can you add such things into your documentation?

Most helpful comment

@JuKu I think recommended way would be :

//using default allocator
ByteBuf buf = ctx.alloc().buffer();

or

ByteBuf buf = channel.alloc().buffer();

or

ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer();

all this 3 methods are doing the same. Your approach is also fine, however it is uses unpooled allocator. While Netty default allocator in latest version is Pooled (should be a bit faster against Unpooled).

All 4 comments

Set the pooled buffer allocator in your bootstrap then alloc the buffers via context / channel reference. There are plenty of usages in the user guide ( http://netty.io/wiki/user-guide-for-4.x.html ) or examples ( https://github.com/netty/netty/tree/4.1/example ).

As I mentioned in https://github.com/netty/netty/issues/5793 please use SO for questions regarding usage.

@johnou In your documentation / examples isnt any buffer allocator in the bootstrap set.

ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
    .channel(NioServerSocketChannel.class) // (3)
    .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new DiscardServerHandler());
        }
    })
    .option(ChannelOption.SO_BACKLOG, 128)          // (5)
    .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

    // Bind and start to accept incoming connections.
    ChannelFuture f = b.bind(port).sync(); // (7)

I think it doesnt makes sense, if every user post an question at stackoverflow. The documentation is responsible to answer such questions!
But if i am honestly, the documentation answer only such beginner questions, no advanced things.
The documentation does only contains some specific examples yet, or?

@JuKu I think recommended way would be :

//using default allocator
ByteBuf buf = ctx.alloc().buffer();

or

ByteBuf buf = channel.alloc().buffer();

or

ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer();

all this 3 methods are doing the same. Your approach is also fine, however it is uses unpooled allocator. While Netty default allocator in latest version is Pooled (should be a bit faster against Unpooled).

as @doom369 suggests generally you want to use the allocator from the ChannelHandlerContext or Channel if available, unless you need a specific allocator for a good reason (static allocations, wrapping heap based arrays, etc..)

Was this page helpful?
0 / 5 - 0 ratings