In Java, handling time-based caching can be a challenge. Keys may expire after a certain duration, and automatically purging these expired entries can become necessary.
One solution to this problem is to leverage the power of Google Collections, now known as Guava. Guava's MapMaker class provides a convenient mechanism for creating maps with expiring keys.
ConcurrentMap<Key, Graph> graphs = new MapMaker() .concurrencyLevel(4) .softKeys() .weakValues() .maximumSize(10000) .expiration(10, TimeUnit.MINUTES) .makeComputingMap( new Function<Key, Graph>() { public Graph apply(Key key) { return createExpensiveGraph(key); } });
With MapMaker, you can specify various parameters:
Guava has since deprecated some of these MapMaker methods in favor of CacheBuilder:
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder() .maximumSize(10000) .expireAfterWrite(10, TimeUnit.MINUTES) .build( new CacheLoader<Key, Graph>() { public Graph load(Key key) throws AnyException { return createExpensiveGraph(key); } });
CacheBuilder offers a more concise and updated API for managing time-based caching in Java.
The above is the detailed content of How to Create a Time-Based Expiring Cache in Java using Guava?. For more information, please follow other related articles on the PHP Chinese website!