带有过期键的 Java 基于时间的地图/缓存 [英] Java time-based map/cache with expiring keys

查看:26
本文介绍了带有过期键的 Java 基于时间的地图/缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你们中有人知道在给定超时后自动清除条目的 Java Map 或类似的标准数据存储吗?这意味着老化,旧的过期条目会自动老化".

Do any of you know of a Java Map or similar standard data store that automatically purges entries after a given timeout? This means aging, where the old expired entries "age-out" automatically.

最好在可通过 Maven 访问的开源库中?

Preferably in an open source library that is accessible via Maven?

我知道自己实现该功能的方法,并且过去已经实现过多次,所以我不是在寻求这方面的建议,而是寻求一个好的参考实现的指针.

I know of ways to implement the functionality myself and have done it several times in the past, so I'm not asking for advice in that respect, but for pointers to a good reference implementation.

WeakReference 的解决方案,例如WeakHashMap 不是一个选项,因为我的密钥很可能是非实习字符串,我想要一个不依赖于垃圾收集器的可配置超时.

WeakReference based solutions like WeakHashMap are not an option, because my keys are likely to be non-interned strings and I want a configurable timeout that's not dependent on the garbage collector.

Ehcache 也是我不想依赖的选项,因为它需要外部配置文件.我正在寻找纯代码解决方案.

Ehcache is also an option I wouldn't like to rely on because it needs external configuration files. I am looking for a code-only solution.

推荐答案

是的.Google Collections 或 Guava 现在被称为 MapMaker 可以做到这一点.

Yes. Google Collections, or Guava as it is named now has something called MapMaker which can do exactly that.

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

更新:

从 guava 10.0(2011 年 9 月 28 日发布)开始,许多 MapMaker 方法已被弃用,取而代之的是新的 CacheBuilder:

As of guava 10.0 (released September 28, 2011) many of these MapMaker methods have been deprecated in favour of the new 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);
          }
        });

这篇关于带有过期键的 Java 基于时间的地图/缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆