Home > Java > javaTutorial > body text

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

Barbara Streisand
Release: 2024-11-20 13:34:17
Original
356 people have browsed it

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);
         }
       });
Copy after login

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);
          }
        });
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template