I was looking at PooledByteBufAllocator code, as part of its default initialization it seems to prefer direct buffer. If this allocator starts with direct buffer and runs out of space, does it switch to heap?
@anuchandy no it does not.
thanks @normanmaurer. I've following code for ByteBuf to ByteBuffer conversion -
public static ByteBuffer toByteBuffer(ByteBuf buffer) {
if (buffer.isDirect()) {
return buffer.nioBuffer();
} else {
final byte[] bytes = new byte[buffer.readableBytes()];
buffer.getBytes(buffer.readerIndex(), bytes);
return ByteBuffer.wrap(bytes);
}
}
if I'm using PooledByteBufAllocator, under what cases else block can hit? I mean the circumstances in which PooledByteBufAllocator direct buffer preference could be rejected.
Also is there a configuration where users of my application could use to tell PooledByteBufAllocator to not to use direct buffer?
Some code may just wrap an byte[] so produce a non-direct buffer. Also even if you configure PooledByteBufAllocator to prefer heap buffers some code may still request a direct buffer (because it need it).
Also @anuchandy you can do ByteBuffer bb = buffer.nioBuffer() regardless of what kind of ByteBuf it is. It will perform similar logic to your example implicitly. Watch out though that the returned ByteBuffer will share the underlying data (not copy as in the latter part of your example) ... this is true for both direct/non-direct cases but not necessarily if it's a composite.
Thanks @normanmaurer
Thanks @njhill, didn't know that ByteBuf::nioBuffer() works for both direct and heap based ByteBuf. This is great news, so this ensure less GC pressure then. Yes we've necessary logic to release the source ByteBuf instance to pool which we do only after we're done with derived ByteBuffer.