3

相关用例:

read input 

if (correlation-id is already generated for this input) 
{ 
   lookup the correlation-id from the cache; 
   return correlation-id; 
} 

else 
{ 
   generate the correlation-id; 
   cache it; 
   return correlation-id; 
} 

约束: - 输入记录的数量可以达到 500K,因此不想使用强引用。- 目前不想生成单向哈希(我知道如果我们使用单向哈希,则不需要缓存)

有人可以告诉我如何为此使用 ComputingMap。我问这个是因为 javadoc 中有一条注释说“它对弱/软键使用身份相等”。

4

1 回答 1

3

使用 Google Guava/Collection 类和软键或弱键或值,您的键需要是地图的强引用才能使用 equals() 而不是 == 来查找缓存值。如果您有弱/软键,则使用身份完成查找,因此您总是会遇到缓存未命中。因此,如果您希望垃圾收集器从缓存中 GC 项目,那么您需要使值变软或弱。

我知道 Google 将来会添加一个 Equivalence 功能,因此您可以说明您是否需要 equals() 或 ==,而不是通过选择强引用、弱引用或软引用来为您做出选择。

由于您的 Tuple 对象实现了 equals() 和 hashCode(),那么您只需执行

new MapMaker()
    .softValues()
    .makeComputingMap(new Function<Tuple,String>() {
                                         public String apply(Tuple t) {
                                             // generate the correlation-id
                                         }
                                    });
于 2010-01-15T01:11:05.543 回答