A high performance caching library for Java providing Google Guava-inspired API with advanced eviction policies and comprehensive features
npx @tessl/cli install tessl/maven-com-github-ben-manes-caffeine--caffeine@3.2.0Caffeine is a high-performance, near-optimal in-memory caching library for Java that provides a Google Guava-inspired API with significant performance improvements. The library offers flexible cache construction with optional features including automatic loading of entries, size-based eviction using frequency and recency algorithms, time-based expiration, asynchronous refresh capabilities, key/value reference wrapping, eviction notifications, write propagation, and comprehensive cache access statistics.
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.2.0</version>
</dependency>import com.github.benmanes.caffeine.cache.*;
import com.github.benmanes.caffeine.cache.stats.*;
// Specific imports
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.AsyncCache;
import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.github.benmanes.caffeine.cache.CacheLoader;import com.github.benmanes.caffeine.cache.*;
import java.time.Duration;
// Create a simple cache
Cache<String, String> cache = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(Duration.ofMinutes(10))
.build();
// Manual cache operations
cache.put("key", "value");
String value = cache.getIfPresent("key");
// Create a loading cache
LoadingCache<String, String> loadingCache = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(Duration.ofMinutes(10))
.build(key -> fetchValueFromDatabase(key));
// Automatic loading
String loadedValue = loadingCache.get("key");Caffeine is built around several key components:
Caffeine class provides fluent configuration API with 30+ optionsComprehensive builder API for configuring cache instances with size limits, expiration policies, reference strength, listeners, and statistics.
// Static factory method
public static Caffeine<Object, Object> newBuilder()
// Terminal methods for cache creation
public <K1 extends K, V1 extends V> Cache<K1, V1> build()
public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(CacheLoader<? super K1, V1> loader)
public <K1 extends K, V1 extends V> AsyncCache<K1, V1> buildAsync()
public <K1 extends K, V1 extends V> AsyncLoadingCache<K1, V1> buildAsync(CacheLoader<? super K1, V1> loader)Manual and loading cache interfaces for synchronous cache operations with automatic value computation.
// Cache interface - manual operations
public interface Cache<K, V> {
V getIfPresent(K key);
V get(K key, Function<? super K, ? extends V> mappingFunction);
void put(K key, V value);
void invalidate(K key);
}
// LoadingCache interface - automatic loading
public interface LoadingCache<K, V> extends Cache<K, V> {
V get(K key);
Map<K, V> getAll(Iterable<? extends K> keys);
}Asynchronous cache interfaces returning CompletableFuture for non-blocking cache operations.
// AsyncCache interface
public interface AsyncCache<K, V> {
CompletableFuture<V> getIfPresent(K key);
CompletableFuture<V> get(K key, Function<? super K, ? extends V> mappingFunction);
void put(K key, CompletableFuture<V> valueFuture);
}
// AsyncLoadingCache interface
public interface AsyncLoadingCache<K, V> extends AsyncCache<K, V> {
CompletableFuture<V> get(K key);
CompletableFuture<Map<K, V>> getAll(Iterable<? extends K> keys);
}Runtime inspection and control of cache behavior including eviction, expiration, and refresh policies.
public interface Policy<K, V> {
boolean isRecordingStats();
Optional<Eviction<K, V>> eviction();
Optional<Expiration<K, V>> expireAfterAccess();
Optional<Expiration<K, V>> expireAfterWrite();
Optional<VarExpiration<K, V>> expireVariably();
}Comprehensive cache performance tracking with immutable statistics snapshots and configurable counters.
public final class CacheStats {
public long requestCount();
public long hitCount();
public double hitRate();
public long missCount();
public double missRate();
public long loadCount();
public double averageLoadPenalty();
public long evictionCount();
}Key functional interfaces for cache value loading, removal listening, entry weighing, and custom expiration.
@FunctionalInterface
public interface CacheLoader<K, V> {
V load(K key) throws Exception;
}
@FunctionalInterface
public interface RemovalListener<K, V> {
void onRemoval(K key, V value, RemovalCause cause);
}
@FunctionalInterface
public interface Weigher<K, V> {
int weigh(K key, V value);
}String interning functionality for any immutable type, providing memory-efficient canonical instance management.
@FunctionalInterface
public interface Interner<E> {
E intern(E sample);
}
// Static factory methods
public static <E> Interner<E> newStrongInterner();
public static <E> Interner<E> newWeakInterner();public enum RemovalCause {
EXPLICIT, // Manual removal (wasEvicted() = false)
REPLACED, // Value replaced (wasEvicted() = false)
COLLECTED, // Garbage collected (wasEvicted() = true)
EXPIRED, // Time-based expiration (wasEvicted() = true)
SIZE; // Size-based eviction (wasEvicted() = true)
public abstract boolean wasEvicted();
}public class CaffeineSpec {
public static CaffeineSpec parse(String spec);
public Caffeine<Object, Object> toCaffeine();
}
@FunctionalInterface
public interface Ticker {
long read();
static Ticker systemTicker();
}
@FunctionalInterface
public interface Scheduler {
Future<?> schedule(Executor executor, Runnable command, long delay, TimeUnit unit);
static Scheduler systemScheduler();
}