Building a Standalone In-Memory Cache with Expiration Support

This article explains how to create a simple single‑node in‑memory cache that supports per‑entry expiration by defining a generic cache interface and implementing it with Caffeine, using ConcurrentHashMap to store multiple caches keyed by expiration time.

ZhiKe AI
ZhiKe AI
ZhiKe AI
Building a Standalone In-Memory Cache with Expiration Support

Background – Redis is widely used for caching, but in some scenarios a full Redis deployment is unnecessary for a single‑process application. The article proposes using existing Java caching libraries such as Guava or Caffeine to build a lightweight cache that mimics Redis’s expiration feature.

Implementation Overview

The first step is to define a generic CacheTemplate<K, V> interface, which abstracts basic cache operations and enables easy swapping of the underlying cache implementation:

public interface CacheTemplate<K, V> {
    V get(K key);
    void set(K key, V value, long time, TimeUnit timeUnit);
    boolean delete(K key);
    boolean exist(K key);
}

Defining the interface illustrates the benefit of programming to an interface, allowing future replacement of the cache backend without changing client code.

Caffeine‑Based Cache Template

The concrete implementation CaffeineCacheTemplate<K, V> uses Caffeine to provide per‑entry expiration. Key components include:

A static Map<String, Cache<Object, Object>> cache that holds multiple Caffeine caches, each identified by a unique cache key derived from the expiration duration.

A static Map<Object, String> cacheKeys that maps the logical key to the corresponding cache key.

A constant MAXIMUM_SIZE = 10000 limiting each Caffeine cache’s size.

get retrieves the appropriate Caffeine cache via getCache(key), then calls getIfPresent. If the value exists, it is returned; otherwise null is returned.

set converts the supplied expiration time and timeUnit to nanoseconds, builds a unique cacheKey, and either creates a new Caffeine cache with expireAfterWrite(time, timeUnit) and maximumSize(MAXIMUM_SIZE) or reuses an existing one. The logical key is stored in cacheKeys, and the value is put into the selected Caffeine cache.

delete obtains the cache for the key, removes the mapping from cacheKeys, and calls invalidate(key) on the underlying Caffeine cache.

exist checks whether the cache contains the key by calling getIfPresent and returning a boolean.

The helper method getCache(K key) looks up the cache key from cacheKeys, retrieves the corresponding Caffeine cache from cache, and returns it, or null if no cache exists.

Design Rationale

The approach creates a separate Caffeine cache for each distinct expiration duration, storing these caches in a global map. This allows different entries to have independent lifetimes while keeping the overall implementation simple and thread‑safe (methods are synchronized). The use of ConcurrentHashMap ensures concurrent access to the cache maps.

Conclusion

The resulting code provides a compact, single‑node cache framework with expiration support, demonstrating how to combine interface‑driven design with Caffeine’s flexible expiration policies to replace a Redis‑like cache in lightweight Java applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaCacheCaffeineIn-MemoryInterfaceExpiration
ZhiKe AI
Written by

ZhiKe AI

We dissect AI-era technologies, tools, and trends with a hardcore perspective. Focused on large models, agents, MCP, function calling, and hands‑on AI development. No fluff, no hype—only actionable insights, source code, and practical ideas. Get a daily dose of intelligence to simplify tech and make efficiency tangible.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.