1

I need a simple caching mechanism.

I want to keep up to the last 100 most-recent items that were added, but no more than that limit. As I add another item, I want the collection to automatically delete the 101st item. Imagine pushing LifeSaver candies through a tube – as I add another candy at one end of the tube, at the other end another candy will fall out.

It would be simple to write my own. My "add" method would first delete the oldest item before performing tho "add". I just wonder if there is already such a class written.

I looked at the bundled Collection classes, List, Queue, and so on. I looked a Google Guava as well. But none seem to have this simple feature.

This is a difficult topic to google, as I do not know the jargon for this behavior.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • You are looking for something like a Fifo: http://stackoverflow.com/questions/9580457/fifo-class-in-java – DA. Feb 11 '14 at 08:33
  • Take a look here: http://stackoverflow.com/questions/3355216/which-java-collection-should-i-use-to-implement-a-thread-safe-cache – Ashot Karakhanyan Feb 11 '14 at 08:33
  • This is already answered here: http://stackoverflow.com/questions/5498865/size-limited-queue-that-holds-last-n-elements-in-java – Kostas Kryptos Feb 11 '14 at 08:39
  • 1
    @DA A FIFO queue is close, but I need the extra feature of *automatically* deleting the oldest item when a new one is added. The [correct answer](http://stackoverflow.com/a/21696750/642706) has links to two such classes. Thanks to everyone for links. And sorry for a duplicate question – as I said, not easy to search when I didn't know the terms. I did update some of the other questions with current info. – Basil Bourque Feb 11 '14 at 10:33
  • http://stackoverflow.com/a/1963881/1953590 is the correct answer if you don't want to involve any third-party libraries. – Kevin Krumwiede Feb 25 '15 at 01:01

1 Answers1

11

Apache Commons – CircularFifoQueue

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

I guess this is the behavior what you are looking for. Its from the Apache commons collections (link)

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Akkusativobjekt
  • 2,005
  • 1
  • 21
  • 26
  • 1
    Thanks for your correct answer. Using that class name I was able to find that *Google Guava* version 15 (circa 2013-10) gained an [`EvictingQueue`](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/EvictingQueue.html) (good name!) class with similar behavior. See article, [Guava 15 – New features](http://www.javacodegeeks.com/2013/10/guava-15-new-features.html). – Basil Bourque Feb 11 '14 at 10:07