Dynamic ByteBuffer ?


In the code below, a socket channel is reading the input data. I would like to know if it is possible to have a dynamic ByteBuffer. And what if the input data is bigger than the allocated space in the buffer ?
Thank you.

protected static int BYTE_BUFFER_SIZE = 1000;
private ByteBuffer readBuffer = ByteBuffer.allocate(BYTE_BUFFER_SIZE);
public someFunction() {
     SocketChannel socketChannel = (SocketChannel) key.channel();
     int numRead;
     try {
           numRead = socketChannel.read(this.readBuffer);
Who is Participating?
objectsConnect With a Mentor Commented:
no you can't. If there is more to read than is available then the additional data will remain in the stream waiting to be read
VenabiliConnect With a Mentor Commented:
objects is correct of course. Just a small addition (which should be logical from what he already said but still should be said):

And that's why when you read from a socket, you usually do it with a loop of some type so you can get the full content that is sent to you. In this case what you can have is a dynamicly sized List or some other Ordered collection type (or even SrtingBuffer if this is what you read) where you can collect the data read with the ByteBuffer - and then to work with the full sized data.
CEHJConnect With a Mentor Commented:
If you want to collect what's essentially 'binary' data, you could use a ByteArrayOutputStream
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

matthew016Author Commented:
So if the ByteBuffer is fixed, what is a good size to allocate ?
I have seen programmers setting it to e.g. 8192, why not 8000 or 8500 ? It's some exact number corresponding to the memory I guess ?

1. How do I compute such a number ?
2. Will the size of the buffer have an impact on my software ?
depends on lots of things, for example how much data you are expecting to be reading.
If its only a small amount then you don't want it too big, or its just wasted.
I prefer using things like 4096 or 8192... makes a full number of KB of data... :)

>1. How do I compute such a number ?
Guess and try and test. No algorithm really. Whenever I need a buffer, I usually runa  few tests to see how it behaves in each case.

>2. Will the size of the buffer have an impact on my software ?
Really depends on what you are doing after this. Too small buffer can slow the program if there is some extensive processing after this which is not really dependant on the size of the data... too big one is not used if you do not have enough data(as CEHJ already mentioned). And sometimes a large buffer is a real trouble for the memory - in multithreaded applications especially, sometimes if you go for way too big buffer, you run into OutOfMemoryExceptions.
OOps - that was objects that mentioned the big buffer/small data thing - sorry :)
All Courses

From novice to tech pro — start learning today.