Alex Rivera | Logout

Easy, simple to use LRU cache in java

Asked 2008-10-22T08:27:04.337
82

I know it's simple to implement, but I want to reuse something that already exist.

Problem I want to solve is that I load configuration (from XML so I want to cache them) for different pages, roles, ... so the combination of inputs can grow quite much (but in 99% will not). To handle this 1%, I want to have some max number of items in cache...

Till know I have found org.apache.commons.collections.map.LRUMap in apache commons and it looks fine but want to check also something else. Any recommendations?

Edit
Report

1 Answer

36

This is an old question, but for posterity I wanted to list ConcurrentLinkedHashMap, which is thread safe, unlike LRUMap. Usage is quite easy:

ConcurrentMap<K, V> cache = new ConcurrentLinkedHashMap.Builder<K, V>()
    .maximumWeightedCapacity(1000)
    .build();

And the documentation has some good examples, like how to make the LRU cache size-based instead of number-of-items based.

answered 2011-09-28T13:41:04.600

Your Answer