Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best resizable circular byte buffer available in Java?

Tags:

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?

like image 976
Wouter Lievens Avatar asked Nov 28 '08 12:11

Wouter Lievens


People also ask

What is ring buffer in Java?

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.

What is a buffer byte?

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.

How do I declare ByteBuffer?

ByteBuffer buf = ByteBuffer. allocate(1000);

How does a ring buffer work?

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.


1 Answers

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.

like image 88
VonC Avatar answered Oct 26 '22 05:10

VonC