I have a streaming time series, of which I am interested in keeping the last 4 elements, which means I want to be able to pop the first, and add to the end. Essentially what I need is a ring buffer.
Which Java Collection is the best for this? Vector?
A ring buffer is a data structure that is treated as circular although it its implementation is linear. A circular buffer is typically used as a data queue. A circular buffer is a popular way to implement a data stream because the code can be compact.
Applications. Ring Buffers are common data structures frequently used when the input and output to a data stream occur at different rates.
A Circular Queue is a special version of queue where the last element of the queue is connected to the first element of the queue forming a circle. The operations are performed based on FIFO (First In First Out) principle. It is also called 'Ring Buffer'.
The ring buffer does not require any "locking" (mutual exclusion mechanism) as long as the following restrictions are met: Only one thread/interrupt can produce data into the ring buffer. Only one thread/interrupt can consume data from the ring buffer.
Consider CircularFifoBuffer from Apache Common.Collections. Unlike Queue you don't have to maintain the limited size of underlying collection and wrap it once you hit the limit.
Buffer buf = new CircularFifoBuffer(4); buf.add("A"); buf.add("B"); buf.add("C"); buf.add("D"); //ABCD buf.add("E"); //BCDE
CircularFifoBuffer will do this for you because of the following properties:
However you should consider it's limitations as well - for example, you can't add missing timeseries to this collection because it doens't allow nulls.
NOTE: When using current Common Collections (4.*), you have to use Queue. Like this:
Queue buf = new CircularFifoQueue(4);
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