use*_*419 2 java hashmap guava
我指的是以下内容:
https://code.google.com/p/guava-libraries/wiki/CachesExplained
我有一个哈希映射,目前定义如下:
Map<String, String> barcodeMap = Maps.newHashMap(); //Declaring hashmap
while ((nextLine = reader.readNext()) != null) // populating hashmap
{
barcodeMap.put(nextLine[0], nextLine[1]);
}
Run Code Online (Sandbox Code Playgroud)
我希望我的地图用缓存实现,它一次只存储两个小时,我试着阅读我放的链接中的例子,但我不明白我将如何更改当前的地图.我明白我必须填充地图然后使用驱逐,但我不明白我将如何更改我当前的代码.
这很简单,虽然我可以看到混乱,因为他们给出的所有示例都假设你使用CacheLoader来填充Cache,如果你之前使用的是Map,那么你就不会这样.
所以给出的例子是:
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.removalListener(MY_LISTENER)
.build(
new CacheLoader<Key, Graph>() {
public Graph load(Key key) throws AnyException {
return createExpensiveGraph(key);
}
});
Run Code Online (Sandbox Code Playgroud)
您正在直接插入地图,而不是使用加载程序,因此请删除加载部分:
Cache<Key, Graph> graphs = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.removalListener(MY_LISTENER)
.build();
Run Code Online (Sandbox Code Playgroud)
删除项目时是否需要通知?
Cache<Key, Graph> graphs = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();
Run Code Online (Sandbox Code Playgroud)
不想要固定大小的缓存,并且只想按时限制它?
Cache<Key, Graph> graphs = CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();
Run Code Online (Sandbox Code Playgroud)
你说你想要2个小时,你的版本是String,String,所以...
Cache<String, String> graphs = CacheBuilder.newBuilder()
.expireAfterWrite(2, TimeUnit.HOURS)
.build();
Run Code Online (Sandbox Code Playgroud)