Cache in Java With LRU Eviction Policy

Introduction

LRU (or Least Recently Used) is a cache eviction strategy, wherein if the cache size has reached the maximum allocated capacity, the least recently accessed objects in the cache will be evicted. Also, the objects in the cache could be accessed by multiple threads in an application so is very important that the cache has good synchronization mechanism in-built. This article describes the implementation of a Java based cache with LRU eviction strategy; but fundamentally applies to any programming language.

Background

Many a times, developers embed caching frameworks in their application like Ehcache (which is a great library for general purpose, in-memory caching). But there are ocassions when there is no liberty to use such frameworks or libraries; like cases for lightweight Java applications or mobile applications which are targeted to run on minimal memory footprint (or sometimes due to delivery deadlines there is no extra time learn and configure 3rd party caching frameworks and deploy to production). In these times, such a simple, light-weight LRUCache class can be used and with sufficient unit test coverage the cache can be heaviliy relied upon.