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.

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.