Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ring Buffer in Java

Tags:

java

buffer

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?

like image 818
Truba Avatar asked Sep 01 '11 04:09

Truba


People also ask

What is meant by ring buffer?

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.

Where are ring buffers used?

Applications. Ring Buffers are common data structures frequently used when the input and output to a data stream occur at different rates.

Which queues is also called ring buffer?

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'.

Why is ring buffer lock free?

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.


1 Answers

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:

  • CircularFifoBuffer is a first in first out buffer with a fixed size that replaces its oldest element if full.
  • The removal order of a CircularFifoBuffer is based on the insertion order; elements are removed in the same order in which they were added. The iteration order is the same as the removal order.
  • The add(Object), BoundedFifoBuffer.remove() and BoundedFifoBuffer.get() operations all perform in constant time. All other operations perform in linear time or worse.

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); 
like image 148
Andrey Taptunov Avatar answered Oct 08 '22 14:10

Andrey Taptunov