dev@grizzly.java.net

Re: how to optimize the ByteBuffer memory ?

From: Oleksiy Stashok <Oleksiy.Stashok_at_Sun.COM>
Date: Fri, 14 Nov 2008 15:04:04 +0100

Hi Sebastien,

> I have to snippet of codes. I,m looking for a way to optimize the
> ByteBuffer realocation if possible.
>
>
> Part1 in ProtocolParser
>
> // Check if buffer is full
> if (processingBuffer.remaining() ==
> processingBuffer.capacity()) {
> // If full - reallocate
>
> // but check if the max length is attain
> if(processingBuffer.capacity() +
> processingBuffer.remaining()<LIMITBB){
> ByteBuffer newBB =
> ByteBufferFactory.allocateView(
> processingBuffer.capacity() * 2,
> processingBuffer.isDirect());
> newBB.put(processingBuffer);
> processingBuffer = newBB;
> WorkerThread workerThread = (WorkerThread)
> Thread.currentThread();
> workerThread.setByteBuffer(processingBuffer);
> } else {
>
> s_logger.info("BUFFER max length was
> reached");
>
> processingBuffer.clear();
>
> maxBufferReached = true;
>
> return maxBufferReached;
> }
> }
>
the code looks fine.
Though, if you have big messages, I'd suggest, if it's possible, to
not store WHOLE the message in the buffer. Work in stream-like manner.

> Part 2 sending data to the clients
>
> public class Client ....
>
> public void sendToClient(StringBuffer sb) {
>
> ByteBuffer writeBuffer =
> ByteBuffer.allocateDirect(sb.toString().getBytes().length);
>
> writeBuffer.put(sb.toString().getBytes());
>
> writeBuffer.flip();
>
> ......
> }
It's better to use HEAP buffer. (think we discussed this sometimes on
the list).

Thanks.

WBR,
Alexey.

>
>
> }