0

I need to implement a LRU cache with a expiration time of 600s in Java. I searched and found the built-in LinkedHashMap class. It can remove the oldest elements when the size exceeds a limit, but it doesn't have a expiration time for elements.

What I can think of is to associate the timestamp when putting an element into the cache. When retrieving an element, check its timestamp; if the timestamp is older than 600s, then removes the element from the cache and returns 'not-found'.

Any better ideas? Any built-in solutions or best practice? I'd like to avoid reinventing the wheel.

Zain Arshad
  • 1,885
  • 1
  • 11
  • 26
Wang Tuma
  • 893
  • 5
  • 14
  • 24
  • Read the doco https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html about removeEldestEntry. Also https://stackoverflow.com/questions/1936462/java-linkedhashmap-get-first-or-last-entry – TJA Dec 29 '19 at 08:18

2 Answers2

2

How about just using Guava cache.

It supports all of these,

A builder of LoadingCache and Cache instances having any combination of the following features:

  • automatic loading of entries into the cache
  • least-recently-used eviction when a maximum size is exceeded
  • time-based expiration of entries, measured since last access or last write
  • keys automatically wrapped in weak references
  • values automatically wrapped in weak or soft references
  • notification of evicted (or otherwise removed) entries
  • accumulation of cache access statistics
Adwait Kumar
  • 1,552
  • 10
  • 25
0

I suggest not implementing it by yourself, and look at already available implementations:

  1. Guava Cache is a pretty descent option (it wa already recommended so I won't add a link here)
  2. Caffeine A very nice cache implementation.

In case you want to know the difference between the two, read this thread in SO

I believe both will get you covered feature wise. In addition if you're using frameworks like Spring it has in integration with them (later versions use caffeine, older are stick to guava):

Spring Cache

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97