Home >Java >javaTutorial >How to Implement a Time-Based Expiring Map/Cache in Java?

How to Implement a Time-Based Expiring Map/Cache in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-20 13:34:17454browse

How to Implement a Time-Based Expiring Map/Cache in Java?

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!

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