Sobes.tech
Junior

What is the simplest way to implement caching?

sobes.tech AI

Answer from AI

The simplest way to implement caching in Java at the application level is to use HashMap or ConcurrentHashMap (for multithreaded access) as in-memory cache.

Example with ConcurrentHashMap:

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class SimpleCache<K, V> {

    private final ConcurrentHashMap<K, CacheEntry<V>> cache = new ConcurrentHashMap<>();
    private final long ttl; // Time to Live in milliseconds

    public SimpleCache(long ttl) {
        this.ttl = ttl;
    }

    public V get(K key) {
        CacheEntry<V> entry = cache.get(key);
        if (entry == null) {
            return null;
        }

        // Check for expiration
        if (System.currentTimeMillis() > entry.timestamp + ttl) {
            cache.remove(key); // Remove expired entry
            return null;
        }

        return entry.value;
    }

    public void put(K key, V value) {
        cache.put(key, new CacheEntry<>(value, System.currentTimeMillis()));
    }

    public void remove(K key) {
        cache.remove(key);
    }
    
    private static class CacheEntry<V> {
        final V value;
        final long timestamp;

        CacheEntry(V value, long timestamp) {
            this.value = value;
            this.timestamp = timestamp;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // Cache with TTL of 5 seconds
        SimpleCache<String, String> cache = new SimpleCache<>(TimeUnit.SECONDS.toMillis(5));

        cache.put("key1", "value1");
        System.out.println("Retrieved (before expiration): " + cache.get("key1")); // value1

        Thread.sleep(6000); // Wait 6 seconds

        System.out.println("Retrieved (after expiration): " + cache.get("key1")); // null
    }
}

This example demonstrates basic caching with TTL (Time-To-Live) support. More complex scenarios require specialized libraries such as Ehcache or Caffeine, which provide advanced features:

  • Eviction policies (LRU, LFU, etc.)
  • Transparent read and write (read-through, write-through)
  • Cache invalidation on events
  • Distributed caching