简体   繁体   中英

Java Bytebuffer Filling up completely

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?)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM