Java Time-Based Map/Cache with Expiring Keys
In the Java programming language, managing time-based entries in a map or cache is a common requirement. This article provides a solution using Google Collections (Guava) for automatic purging of expired entries.
Solution
Guava's MapMaker class can create a time-based map with adjustable expiration settings. The MapMaker API allows customization of various parameters, such as:
Usage Example
The following code snippet demonstrates how to create a concurrent time-based map:
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); } });
In this example, the map automatically purges expired entries every 10 minutes.
Update
In Guava 10.0 and later, the MapMaker methods have been deprecated in favor of the 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); } });
The above is the detailed content of How Can I Create a Time-Based Expiring Map or Cache in Java Using Guava?. For more information, please follow other related articles on the PHP Chinese website!