Skip to content
Advertisement

Growing ByteBuffer

Has anyone has ever seen an implementation of java.nio.ByteBuffer that will grow dynamically if a putX() call overruns the capacity?

The reason I want to do it this way is twofold:

  1. I don’t know how much space I need ahead of time.
  2. I’d rather not do a new ByteBuffer.allocate() then a bulk put() every time I run out of space.

Advertisement

Answer

In order for asynchronous I/O to work, you must have continuous memory. In C you can attempt to re-alloc an array, but in Java you must allocate new memory. You could write to a ByteArrayOutputStream, and then convert it to a ByteBuffer at the time you are ready to send it. The downside is you are copying memory, and one of the keys to efficient IO is reducing the number of times memory is copied.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement