Home > Java > javaTutorial > How to Create a Time-Based Expiring Map in Java?

How to Create a Time-Based Expiring Map in Java?

Barbara Streisand
Release: 2024-11-27 14:35:12
Original
256 people have browsed it

How to Create a Time-Based Expiring Map in Java?

Java Time-Based Map/Cache with Expiring Keys

Q: Is there a built-in Java Map or similar data structure that automatically removes entries after a specified interval?

A: Yes, Google Collections (now known as Guava) provides a MapMaker class with the desired functionality:

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

Note: As of Guava 10.0, the MapMaker methods mentioned above are deprecated in favor of the CacheBuilder class:

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 CacheBuilder provides additional flexibility and a more modern API for managing cache behavior.

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