This library provides a simple LRU cache based on a linked hash map.
This library is hosted in the Maven Central Repository. You can use it with the following coordinates:
<dependency>
<groupId>net.markenwerk</groupId>
<artifactId>utils-lrucache</artifactId>
<version>1.0.1</version>
</dependency>
Consult the usage description and Javadoc for further information.
As every Java programmer should know, it is possible to create a simple LRU cache from a LinkedHashMap
with a few lines of code. The goal of this library is to provide a ready made LRU cache, so that is isn't necessary to reproduce these few lines of code every time and have an appropriately named class.
This library provides the simple LruCache
which is a LinkedHashMap
that is configured to hold it's entries in access order and evicts the least recently accessed entry, if the configured cache size is exceeded.
// the desired cache size
int cacheSize = ...
// a map that never holds more than cacheSize elements
Map<String, Object> cache = new LruCache<>(cacheSize);
A LruCache
can be created with a LruCacheListener
that gets notified, when an entry is evicted from the LruCache
.
// the desired cache size
int cacheSize = ...
// a map that never holds more than cacheSize elements
Map<String, Object> cache = new LruCache<>(
cacheSize,
entry -> System.out.println(entry.getKey() + " got evicted")
);