Home >Java >javaTutorial >How to Create a Time-Based Expiring Map in Java?

How to Create a Time-Based Expiring Map in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-27 14:35:12223browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn