Home >Java >javaTutorial >How to Create a Time-Based Expiring Map in Java?
Java Time-Based Map/Cache with Expiring Keys
Q: Is there a built-in Java Map or similar data structure that automatically removes entries after a specified interval?
A: Yes, Google Collections (now known as Guava) provides a MapMaker class with the desired functionality:
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); } });
Note: As of Guava 10.0, the MapMaker methods mentioned above are deprecated in favor of the CacheBuilder class:
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 CacheBuilder provides additional flexibility and a more modern API for managing cache behavior.
The above is the detailed content of How to Create a Time-Based Expiring Map in Java?. For more information, please follow other related articles on the PHP Chinese website!