10

I'm looking for a Java class that implements Collection and loses oldest elements when I add() a new one, if total number of elements is bigger than X. Does it exist or I have to implement it myself?

I need a thread-safe one.

Boann
  • 48,794
  • 16
  • 117
  • 146
yegor256
  • 102,010
  • 123
  • 446
  • 597
  • 2
    Possible duplicate of [Java - Ring Buffer](http://stackoverflow.com/questions/7266042/java-ring-buffer) – DavidPostill Jul 31 '14 at 13:09
  • 1
    possible duplicate of [Size-limited queue that holds last N elements in Java](http://stackoverflow.com/questions/5498865/size-limited-queue-that-holds-last-n-elements-in-java) – Andrew Stubbs Jul 31 '14 at 13:10
  • Possible duplicate of [Thread-safe circular buffer in Java](http://stackoverflow.com/questions/11079210/thread-safe-circular-buffer-in-java) – DavidPostill Jul 31 '14 at 13:13
  • [This](http://www.museful.net/2012/software-development/circulararraylist-for-java) might help – Mustafa sabir Jul 31 '14 at 13:15

4 Answers4

16

Apart from Linkedhasmap if you are looking for list type solution, Google guava has EvictingQueue. And for thread safety you must wrap it in a synchronized wrapper (Queues#synchronizedQueue).

EvictingQueue<String> q = EvictingQueue.create(3);
Queue<String> syncQ =  Queues.synchronizedQueue(q);
syncQ.add("one");
syncQ.add("two");
syncQ.add("three");
syncQ.add("four");
System.out.println(q); // Prints [two, three, four]
tro
  • 524
  • 4
  • 12
Syam S
  • 8,421
  • 1
  • 26
  • 36
3

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its
oldest element if it is full.

akash
  • 22,664
  • 11
  • 59
  • 87
David Pullar
  • 706
  • 6
  • 18
3

You can use the LinkedHashMap to do precisely that, quoting the Javadoc:

// Sample use: this override will allow the map to grow up to 100 entries and then delete the 
// eldest entry each time a new entry is added, maintaining a steady state of 100 entries.

 private static final int MAX_ENTRIES = 100;

 protected boolean removeEldestEntry(Map.Entry eldest) {
    return size() > MAX_ENTRIES;
 }

for thread safe-ness you can wrap it using Collections.synchronizedmap().

rsp
  • 23,135
  • 6
  • 55
  • 69
0

I've used EvictingQueue added at v.15 of Google Guava to implement Moving Average functionality in the past.

It is not thread-safe though.

dimitrisli
  • 20,895
  • 12
  • 59
  • 63