Friday, October 18, 2013

LruCache in Java

Java collections has LinkedHashMap which is a combination of a HashMap and a linked list which allows for predictable iteration order. There are two options for iteration - Based on insertion order, or based on Access order.

Now to create a Least Recently Used cache, the implementation need to use the access order for iteration and override the hook method removeEldestEntry() which should check the required size of the map to remove entries. I've posted the code in the example below.

Also present in the example is how you should *not* use the map in an multithreaded fashion. The class is not thread-safe and you end up with non deterministic behavior and the size invariant and probably other things go wrong.

2 comments:

i Digital Academy said...

Thanks for sharing the information...
SEO Training in Bangalore | SEO Course Fees | Best SEO Classes - Join SEO Training in Bangalore at i Digital Academy and learn how to increase your website Traffic by
Google Certified Trainers with 100% Placements and affordable course fees. Book a Free Demo!

Alex said...

Download one of these free WordPress templates for business and create a professional website in minutes.