I need a byte buffer class in Java for single-threaded use. I should be able to insert data at the back of the buffer and read data at the front, with an amortized cost of O(1). The buffer should resize when it's full, rather than throw an exception or something.
I could write one myself, but I'd be very surprised if this didn't exist yet in a standard Java package, and if it doesn't, I'd expect it to exist in some well-tested public library.
What would you recommend?
A ring buffer is an efficient FIFO buffer. It uses a fixed-size array that can be pre-allocated upfront and allows an efficient memory access pattern. All the buffer operations are constant time O(1), including consuming an element, as it doesn't require a shifting of elements.
A ByteBuffer is a buffer which provides for transferring bytes from a source to a destination. In addition to storage like a buffer array, it also provides abstractions such as current position, limit, capacity, etc. A FileChannel is used for transferring data to and from a file to a ByteBuffer.
ByteBuffer buf = ByteBuffer. allocate(1000);
Circular buffers (also known as ring buffers) are fixed-size buffers that work as if the memory is contiguous & circular in nature. As memory is generated and consumed, data does not need to be reshuffled – rather, the head/tail pointers are adjusted. When data is added, the head pointer advances.
Not sure if it is "the best", but you have a nice example of Circular Byte buffer here.
Those Java Utilities - OstermillerUtils classes are under GPL license.
This Circular Byte Buffer implements the circular buffer producer/consumer model for bytes. Filling and emptying the buffer is done with standard Java InputStreams and OutputStreams.
Using this class is a simpler alternative to using a PipedInputStream and a PipedOutputStream.
PipedInputStreams and PipedOutputStreams don't support the mark operation, don't allow you to control buffer sizes that they use, and have a more complicated API that requires a instantiating two classes and connecting them.
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