【发布时间】:2014-03-24 21:02:56
【问题描述】:
我正在尝试使用 Guava 缓存来替代 ConcurrentLinkedHashMap。但是我发现,虽然 ConcurrentLinkedHashMap 允许我按插入顺序遍历地图,但 Guava 的 asMap() 方法不会以任何特定顺序返回元素。是我遗漏了什么,还是这个功能根本不可用?
示例(尝试打印键、值和条目):
Cache<Integer, Integer> cache = CacheBuilder.newBuilder().maximumSize(10).initialCapacity(10)
.expireAfterAccess(10000, TimeUnit.SECONDS).build();
cache.put(1, 1);
cache.put(2, 2);
cache.put(3, 3);
cache.put(4, 4);
cache.put(5, 5);
cache.put(6, 6);
Iterator<Integer> iter1 = cache.asMap().keySet().iterator();
System.out.println("Keys");
while (iter1.hasNext())
System.out.println(iter1.next());
System.out.println("Values");
Iterator<Integer> iter2 = cache.asMap().values().iterator();
while (iter2.hasNext())
System.out.println(iter2.next());
System.out.println("Entries");
Iterator<Entry<Integer, Integer>> iter3 = cache.asMap().entrySet().iterator();
while (iter3.hasNext()) {
Entry<Integer,Integer> entry = iter3.next();
System.out.println(entry.getKey() + " " + entry.getValue());
}
打印:
Keys
2
6
1
4
3
5
Values
2
6
1
4
3
5
Entries
2 2
6 6
1 1
4 4
3 3
5 5
【问题讨论】:
-
好问题,看起来答案是“否”...您可以实现自己的
Cache,但不能在CacheBuilder中使用它... -
实现我自己的缓存意味着复制 Guava 缓存已经保存的订购信息。这似乎很尴尬。
-
Cache是一个接口。 Guava 的缓存 AFAICS 根本不保证订购信息。我的意思是你可以实现Cache,这样底层映射就是ConcurrentLinkedHashMap;现在它是ConcurrentHashMap的派生词。但同样,即使你这样做,我也看不出你如何在CacheBuilder中使用它,所以...... -
啊,好吧,我以为你的意思是扩展现有的 LoadingCache。谢谢。
标签: java dictionary caching guava