user3804769
user3804769

Reputation: 509

java 8 - circular buffer

What is the best implementation of a Circular Buffer in Java? I have read other questions but they're old and refer to CircularFifoBuffer which isn't present in Apache Commons Collections 4. Is there a new, widely accepted way to use a circular buffer in Java 8?

Upvotes: 0

Views: 3658

Answers (1)

Anonymous
Anonymous

Reputation: 86359

For a growable circular buffer: java.util.ArrayDeque.

The ArrayDeque class is still a bit overlooked.

You need to define circular buffer more precisely, though. The classical definition suggests a bounded buffer with a capacity that is never changed. I doubt that this is optimal but for a few purposes. This is why my first suggestion is the built-in ArrayDeque class.

From the documentation:

Resizable-array implementation of the Deque interface. Array deques have no capacity restrictions; they grow as necessary to support usage. … This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue.

Since:

1.6

The documentation doesn’t state directly that it’s circular, but it is (I just inspected the source code to be 100 % sure). Since they recommend using it as a queue, it doesn’t really make sense not to make it circular.

For a fixed-capacity circular buffer: Roll your own subclass

If for some reason that I cannot see from here you need a circular buffer that rejects elements beyond some predefined maximum element count, I can’t imagine that it would be hard to write a thin subclass of ArrayDeque that implements the behaviour.

Link: Circular buffer on Wikipedia. Quote:

... a circular buffer... is a data structure that uses a single, fixed-size buffer ...

Upvotes: 0

Related Questions