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.
flip. public ByteBuffer flip() Flips this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded.
wrap. Wraps a byte array into a buffer. The new buffer will be backed by the given byte array; that is, modifications to the buffer will cause the array to be modified and vice versa. The new buffer's capacity will be array.
ByteBuffer limit() methods in Java with Examples nio. ByteBuffer Class is used to set this buffer's limit. If the position is larger than the new limit then it is set to the new limit. If the mark is defined and larger than the new limit then it is discarded.
After you've written to the ByteBuffer, the number of bytes you've written can be found with the position() method. If you then flip() the buffer, the number of bytes in the buffer can be found with the limit() or remaining() methods.
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.
Just as an idea, how about wrapping the ByteBuffer in another class? That class could update and maintain the state you want whenever you perform read or write operations. You may also want to implement locking or some other mechanism to make it thread-safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With