views:

155

answers:

4

Do any of you know of a Java Map or similar standard data store that automatically purges entries after a given timeout? Preferably in an open source library that is accessible via maven?

I know of ways to implement the functionality myself and have done it several times in the past, so I'm not asking for advice in that respect, but for pointers to a good reference implementation.

WeakReference based solutions like WeakHashMap are not an option, because my keys are likely to be non-interned strings and I want a configurable timeout that's not dependent on the garbage collector.

Ehcache is also an option I wouldn't like to rely on because it needs external configuration files. I am looking for a code-only solution.

A: 

It may not be a good solution, but you can always take a look at classes like DelayQueue.

Riduidel
Isn't that the opposite of what I want? *An unbounded blocking queue of Delayed elements, in which an element can only be taken when its delay has expired*
seanizer
Oh yes, you're right, sorry for the misundestanding. I was sure some kind of Queue would do the job.
Riduidel
+2  A: 

Check out Google Collections (now called Guava). It has a map which can timeout entries automatically.

dty
+12  A: 

Yes. Google Collections, or Guava as it is named now has something called MapMaker which can do exactly that.

ConcurrentMap<Key, Graph> graphs = new MapMaker()
   .concurrencyLevel(4)
   .softKeys()
   .weakValues()
   .maximumSize(10000)
   .expiration(10, TimeUnit.MINUTES)
   .makeComputingMap(
       new Function<Key, Graph>() {
         public Graph apply(Key key) {
           return createExpensiveGraph(key);
         }
       });
Shervin
Awesome, I knew Guava had an answer but I couldn't find it! (+1)
seanizer
+2  A: 

Google collections (guava) has the MapMaker in which you can set time limit(for expiration) and you can use soft or weak reference as you choose using a factory method to create instances of your choice.

Emil