10

Is there some collection implementation supporting expiration of the elements.

For example:

Collection<User> cachedUsers = new ExpirableList<User>(10000);

where

public ExpirableList(final long timeout){...}

And after given time (10000ms in this particular example), added elements will be removed from the collection. By using this, we will prevent overflow of our cachedUsers collection.

Kiril Kirilov
  • 11,167
  • 5
  • 49
  • 74

3 Answers3

10

Yes, Guava supports a cache with timed expiration. See Guava Explained's page on caches.

An alternative is an LRU (least-recently used) cache that disposes of the oldest accessed element when a new element is inserted.

Markus Patt
  • 467
  • 3
  • 11
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
3

It's not really clear how you're trying to use the collection, but Guava's CacheBuilder may help you.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

You could implement this by writing a wrapper for, say, a TreeMap where you let the insertion time be the key. On each insert, you could drop the head list which has "timed out".

Using insertion time as an indication on whether or not in should be dropped seems like a bad idea though. It seems better to go with some LRU (least recently used) cache for instance. Such caches are readily available in libraries such as EHCache for instance. Don't reinvent the wheel.

Related questions:

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826