3

I'm trying to create a FIFO (first in first out) data structure in Java, which would have a limited capacity and remove the oldest elements when there is not enough space for new ones. For example:

FIFO<Integer> fifo = new FIFO<Integer>(100); // 100 elements maximum
for (int i = 0; i < 500; i++) {
  fifo.write(i);
}
assert fifo.read() == 400; // elements 0..399 are lost

Am I re-inventing a wheel? Can you recommend some library (or maybe it's part of JDK) that does the same? Thread safety is not important.

yegor256
  • 102,010
  • 123
  • 446
  • 597
  • 1
    [Googling for _java circular buffer_](http://www.google.com/search?q=java+circular+buffer) led me to [this existing Stack Overflow post](http://stackoverflow.com/questions/7266042/java-ring-buffer), which in turn recommends the same [org.apache.commons.collections.buffer.CircularFifoBuffer](http://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections/buffer/CircularFifoBuffer.html) class Fls'Zen suggests below. Of course, if you didn't know in advance that this kind of thing was called a circular or ring buffer, it might've been harder to search for. – Ilmari Karonen Apr 18 '13 at 17:36

1 Answers1

5

Apache's Common.Collections has CircularFifoBuffer which should meet your requirements.

Fls'Zen
  • 4,594
  • 1
  • 29
  • 37