基于Java的时间映射/缓存与过期的密钥 [英] Java time-based map/cache with expiring keys

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

问题描述

您是否知道Java Map或类似的标准数据存储在给定超时后自动清除条目?这意味着老化,旧的过期条目自动退出。



最好在通过Maven访问的开放源代码库?



我知道自己实现功能的方法,并且在过去已经做了很多次,所以我不是在这方面要求建议,而是指向一个很好的参考实现。 p>

WeakReference 解决方案,如 WeakHashMap 不是一个选项,因为我的键可能是非interned字符串,我想要一个不依赖于垃圾收集器的可配置超时。



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

解决方案

是的。 Google收藏集或 Guava 现在命名为 MapMaker ,可以做到这一点。

  ConcurrentMap< Key,Graph> graph = 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

  LoadingCache< Key,Graph>图形= CacheBuilder.newBuilder()
.concurrencyLevel(4)
.weakKeys()
.maximumSize(10000)
.expireAfterWrite(10,TimeUnit.MINUTES)
.build(
new CacheLoader< Key,Graph>(){
public Graph load(Key key)throws AnyException {
return createExpensiveGraph(key);
}
});


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.

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 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 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.

解决方案

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

Update:

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()
    .concurrencyLevel(4)
    .weakKeys()
    .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天全站免登陆