Home  >  Article  >  Java  >  How to Create a Time-Based Expiring Cache in Java using Guava?

How to Create a Time-Based Expiring Cache in Java using Guava?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-21 07:02:16338browse

How to Create a Time-Based Expiring Cache in Java using Guava?

Java Time-Based Map/Cache with Expiring Keys

In Java, handling time-based caching can be a challenge. Keys may expire after a certain duration, and automatically purging these expired entries can become necessary.

One solution to this problem is to leverage the power of Google Collections, now known as Guava. Guava's MapMaker class provides a convenient mechanism for creating maps with expiring keys.

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

With MapMaker, you can specify various parameters:

  • concurrencyLevel: Controls the parallelism within the map.
  • softKeys: Indicates that keys should be held weakly, allowing the garbage collector to reclaim them when possible.
  • weakValues: Similar to softKeys, but for values.
  • maximumSize: Specifies the maximum number of entries in the map.
  • expiration: Sets the expiration duration for entries.

Guava has since deprecated some of these MapMaker methods in favor of 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);
          }
        });

CacheBuilder offers a more concise and updated API for managing time-based caching in Java.

The above is the detailed content of How to Create a Time-Based Expiring 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