Sunday 12 February 2012

Concurrent map with timed out elements using Guava library

Sometimes we have a need to use a map, in which elements live only for a specified amount of time.
We could implement such map ourselves (by overriding removeEldestEntry() from LinkedHashMap or using thread that will be removing elements periodically) but the better idea is to use already existing implementation. Google's guava library (http://code.google.com/p/guava-libraries) is the solution for us.
Let's write some simple unit tests to check the API and verify behaviour:
Map is created using the builder pattern. Apart from specifying the time of elements expiration, it allows among others, setting the maximum map's size or the listener that will be notified each time an entry is removed. As the built object is an instance of Cache, we need to create ConcurrentMap from it using asMap() method.
Two tests verify that added element is removed only when the timeout expires.

1 comment: