9

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
  • 47,128
  • 13
  • 114
  • 141
yegor256
  • 97,508
  • 114
  • 426
  • 573
  • 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

13

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
  • 504
  • 4
  • 11
Syam S
  • 8,281
  • 1
  • 25
  • 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,224
  • 10
  • 57
  • 85
David Pullar
  • 696
  • 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
  • 22,799
  • 6
  • 53
  • 66
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,227
  • 12
  • 57
  • 63