Java 如何使用番石榴CacheBuilder?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19704904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use guava CacheBuilder?
提问by membersound
I'd like to use guavas CacheBuilder
, but cannot find any explicit example how implement this.
我想使用 guavas CacheBuilder
,但找不到任何明确的示例如何实现这一点。
The docs state the following code:
文档说明了以下代码:
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
.maximumSize(1000)
.build(
new CacheLoader<Key, Graph>() {
public Graph load(Key key) throws AnyException {
return createExpensiveGraph(key);
}
});
Question: what is this createExpensiveGraph(key)
method? Is this a method that returns a HashMap<Key, Value>
mapping? What do I have to do with the key
value?
问题:这是什么createExpensiveGraph(key)
方法?这是一个返回HashMap<Key, Value>
映射的方法吗?我与key
价值有什么关系?
Or could I also just return a List<String>
in this method not having to use the key
value in any way?
或者我也可以只List<String>
在此方法中返回 a而不必以key
任何方式使用该值?
采纳答案by Aaron Digulla
The idea of the cache is that you usually have this problem:
缓存的想法是你通常会遇到这个问题:
Graph get(Key key) {
Graph result = get( key );
if( null == result ) {
result = createNewGraph( key );
put( key, result );
}
return result;
}
plus the usual synchronization issues that you have when you use this code in a multi-threaded environment.
加上在多线程环境中使用此代码时遇到的常见同步问题。
Guava does the boilerplate for you; you just have to implement createNewGraph()
. The way Java works, this means you have to implement an interface. In this case, the interface is CacheLoader
.
Guava 为你做样板;你只需要执行createNewGraph()
. Java 的工作方式,这意味着您必须实现一个接口。在这种情况下,接口是CacheLoader
。
If you think that the whole cache is a bit like a map, then CacheLoader
is a callback that gets invoked whenever a key can't be found in the map. The loader will get the key (because it usually contains useful information to create the object that is expected for this key) and it will return the value which get()
should return in the future.
如果您认为整个缓存有点像地图,那么CacheLoader
每当在地图中找不到键时就会调用回调。加载器将获取键(因为它通常包含有用的信息来创建该键所期望的对象)并且它将返回get()
将来应该返回的值。