Reputation: 509
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
Reputation: 86359
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 thanStack
when used as a stack, and faster thanLinkedList
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.
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