Java Time-Based Map/Cache with Expiring Keys
This question seeks a Java implementation that automatically expires entries based on a configurable timeout. The preferred solution avoids weak references, external configuration files, and manual implementation.
Answer
The Guava library provides a solution with its MapMaker class:
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); } });
For Guava version 10.0 and above, use 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); } });
This implementation provides automatic key expiration, ensuring that entries are removed after a specified period.
The above is the detailed content of How to Implement a Time-Based Expiring Map/Cache in Java?. For more information, please follow other related articles on the PHP Chinese website!