Home  >  Article  >  Java  >  How Can I Create a Time-Based Expiring Map or Cache in Java Using Guava?

How Can I Create a Time-Based Expiring Map or Cache in Java Using Guava?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-24 14:42:15512browse

How Can I Create a Time-Based Expiring Map or Cache in Java Using Guava?

Java Time-Based Map/Cache with Expiring Keys

In the Java programming language, managing time-based entries in a map or cache is a common requirement. This article provides a solution using Google Collections (Guava) for automatic purging of expired entries.

Solution

Guava's MapMaker class can create a time-based map with adjustable expiration settings. The MapMaker API allows customization of various parameters, such as:

  • Concurrency level
  • Key and value types (strong/soft/weak)
  • Maximum size
  • Expiration time

Usage Example

The following code snippet demonstrates how to create a concurrent time-based map:

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);
         }
       });

In this example, the map automatically purges expired entries every 10 minutes.

Update

In Guava 10.0 and later, the MapMaker methods have been deprecated in favor of the 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);
          }
        });

The above is the detailed content of How Can I Create a Time-Based Expiring Map or Cache in Java Using Guava?. 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