Reputation: 1682
I am currently using the Java ByteBuffer
ByteBuffer batch = ByteBuffer.allocate(tuple_size * batch_size ) ;
int pos = 0;
int sent = 0;
while ( sent++ < batch_size) {
Event event = (Event) it.next();
batch.put(event.getData(), pos, tuple_size);
pos += tuple_size;
}
return batch.array();
Currently, batch_size is set to 2. My issue is that on the second round, I get an IndexOutofBoundsException which I cannot explain given that, printing out the follwoing details:
System.out.println(pos + " " + batch.capacity() + " " + batch.position() + " " + batch.remaining());
I get: 0 200 0 200 (round 0)
100 200 100 100 (round 1)
which is what one would expect. Now, based on the documentation, it seems that the bound checks do hold:
offset - The offset within the array of the first byte to be read; must be non-negative and no larger than array.length
length - The number of bytes to be read from the given array; must be non-negative and no larger than array.length - offset
How do I completely fill up the buffer? (whilst keeping the underlying buffer to have length tuple_size * batch_size?)
Upvotes: 0
Views: 1989
Reputation: 11977
I think you don't need the pos variable. The put
method is trying to read into event.getData()
at position pos, while I think you want to read event.getData()
from position 0. You can simply use batch.put(event.getData())
to append the whole content of the array into the buffer.
Upvotes: 2
Reputation: 7149
It is not apparent from your question if tuple_size is big enough for event.getData(). If not, that would result in your IndexOutofBoundsException. Perhaps it's off by one?
Another possibility is that your iterator it
only contains one element.
Edit: According to the documentation, you should get a BufferOverflowException if your buffer runs out of space. Quote from the documentation:
This method transfers bytes into this buffer from the given source array. If there are more bytes to be copied from the array than remain in this buffer, that is, if length > remaining(), then no bytes are transferred and a BufferOverflowException is thrown.
This points at that your problem isn't what you expect.
Upvotes: 0