Skip to content

Ehcache / Caffeine

Databases & CachingPerformance / CachingJava

What it is

Ehcache and Caffeine are Java caching libraries that improve application performance by storing frequently accessed data in memory, reducing expensive database or API calls. They support in-memory and optionally persistent caching with flexible eviction and expiration policies.

These libraries allow you to store key-value pairs in a cache with expiration, size limits, eviction policies, and optional persistence. Caffeine is highly optimized for low-latency, high-throughput caching, while Ehcache supports more enterprise features including clustering and JMX monitoring.

Installation

Ehcache: <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.11.9</version> </dependency> Caffeine: <dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> <version>3.1.8</version> </dependency>

Getting started

The smallest useful thing you can do with it, and what each part means.

Simple in-memory cache with Caffeine
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

Cache<String, String> cache = Caffeine.newBuilder()
    .maximumSize(100)
    .expireAfterWrite(10, java.util.concurrent.TimeUnit.MINUTES)
    .build();

cache.put("key1", "value1");
String value = cache.getIfPresent("key1");
System.out.println(value);
Creates a simple Caffeine cache with max size and expiration, then stores and retrieves a value.
Basic Ehcache configuration
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.*;

CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);
Cache<String, String> cache = cacheManager.createCache("myCache",
    CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
        ResourcePoolsBuilder.heap(100)));

cache.put("key1", "value1");
System.out.println(cache.get("key1"));
cacheManager.close();
Creates an Ehcache in-memory cache, adds an entry, retrieves it, and closes the cache manager.

Advanced usage

Where the library earns its place over a simpler alternative.

Loading cache with automatic computation (Caffeine)
Cache<String, String> cache = Caffeine.newBuilder()
    .maximumSize(100)
    .build(key -> "Value for " + key);

System.out.println(cache.get("key1"));
Caffeine can automatically compute values if absent using a mapping function.
Persistent cache with Ehcache
// Configure Ehcache XML for disk persistence
// Allows cache to survive application restarts
Ehcache supports persistent caches on disk, useful for storing large datasets.
Eviction policies
// Caffeine supports LRU, LFU, and W-TinyLFU eviction policies.
// Ehcache supports LRU, LFU, FIFO and custom policies.
Defines how entries are evicted when cache is full or expired.
Statistics and monitoring
System.out.println(cache.stats()); // Caffeine
// Ehcache provides JMX beans for monitoring hits, misses, evictions
Both libraries provide APIs or JMX to monitor cache performance and statistics.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

NullPointerException
Occurs when null keys or values are inserted. Ensure keys and values are non-null.
CacheMiss
In Caffeine, `getIfPresent()` returns null if absent. Use `get(key, mappingFunction)` for automatic loading.
OutOfMemoryError
Occurs if cache grows without bounds. Define size limits and expiration policies.

Best practices

  • Use caches for frequently accessed, immutable or semi-static data.
  • Define reasonable size limits and expiration policies to avoid memory issues.
  • Monitor cache hit/miss ratios to tune performance.
  • For distributed systems, consider clustered cache options (Ehcache Terracotta, Redis integration).
  • Avoid caching sensitive data in plaintext unless encrypted.

Background

Why it exists, and what it was reacting to.

Caching is a key technique to optimize performance and scalability. Ehcache, created in 2003, is a mature and widely-used caching library that supports in-memory, disk, and distributed caching. Caffeine, developed later, provides a high-performance, in-memory cache with efficient algorithms like W-TinyLFU for eviction. Both libraries are used in enterprise Java applications to accelerate data access, reduce latency, and manage load efficiently.