ByteBuffer, what is a clean way to detect if it needs to be flipped

bytebuffer, java

Solution

Encapsulate it in an object - something like the following:

class FlippingByteBuffer {
  ByteBuffer buffer;
  boolean isInUse;
  boolean/Enum mode; //Is it read or write?
}

Then you can use it in your code:

//I'm about to read
FlippingByteBuffer fbb =...;
fbb.beginReading();
doSomething(fbb.getByteBuffer());
fbb.finishReading();

This way you know when something is happening. You could even start using `Lock`s to ensure that the reading and writing block each others etc.

If there's something in the middle, (you're calling something and it's calling back to you), you could put your `FlippingByteBuffer` into a map and/or put it in a `ThreadLocal` (ewww!), or make `FlippingByteBuffer` implement `ByteBuffer`. That might be able to automatically switch between modes (using the read and write methods) depending on what you're doing.

Problem

Is there a clean sure fire way to detect if a ByteBuffer needs flipping? I have a ByteBuffer that is used for packing and unpacking a data stucture and also for storage of bytes to be packed / unpacked. However, if a write operation has just been performed or a read operation has been performed or if a ByteBuffer was passed to my code I cannot guarantee that the buffer is in write mode or read mode with out manually manipulating position and limit. Partial reads and writes also present add to this problem. I have been adopting the convention that the buffer is left in write mode and a duplicate is created and flip'ed for read purposes. When a buffer is passed in to my code is is manually inspected and position and limit are set as they would be in write mode. Surely there is a better way.

Original source