Home > Java > javaTutorial > body text

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

Patricia Arquette
Release: 2024-11-24 14:42:15
Original
513 people have browsed it

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

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

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!

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