使用 Guava 对集合进行缓存过滤器
Cache filter on collection with Guava
我正在开发一个对自动机执行某些操作的程序。自动机由状态(又名节点)和转换(又名边)组成,我需要过滤它们以检索具有特定属性的集合。这个操作很容易实现,但是要执行几次,我会在上面写一点缓存。
在下面的代码片段中有我的实现,我想知道是否是过滤和记忆可观察转换的正确方法。
public class Automata {
private State initial;
private Set <State> states;
private Set <Transition> transitions;
private Supplier <Set <Transition>> observables;
// ...
public Automata() {
this.initial = new State();
this.states = new HashSet <> ();
this.transitions = new HashSet <> ();
this.observables = Suppliers.memoize(() ->
transitions.stream().filter((t) ->
(t.isObservable() == true)).collect(Collectors.toSet()));
}
public getObservables() {
return observables.get();
}
}
问题:
- 是否正确?
- 如果转换改变了其可观察性,此信息是否也会传播到供应商?
抱歉我的英语不好,我希望你已经足够清楚了。
- 是的,没错。
不,您将在转换中所做的更改不会自动传播。对于这种情况,供应商 AFAIK 不适合。
要么你需要像这里一样手动覆盖它:
public void invalidate(){
memorized = Suppliers.memoize(supplier);
}
如果您知道您的更新不会那么频繁并且不需要可靠的读取,memoizeWithExpiration
也可以使用。
或者您只需要使用Cache
,例如:
CacheLoader<Key, Graph> loader = new CacheLoader<Key, Graph>() {
public Graph load(Key key) throws AnyException {
return createExpensiveGraph(key);
}
};
LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder().build(loader);
我正在开发一个对自动机执行某些操作的程序。自动机由状态(又名节点)和转换(又名边)组成,我需要过滤它们以检索具有特定属性的集合。这个操作很容易实现,但是要执行几次,我会在上面写一点缓存。
在下面的代码片段中有我的实现,我想知道是否是过滤和记忆可观察转换的正确方法。
public class Automata {
private State initial;
private Set <State> states;
private Set <Transition> transitions;
private Supplier <Set <Transition>> observables;
// ...
public Automata() {
this.initial = new State();
this.states = new HashSet <> ();
this.transitions = new HashSet <> ();
this.observables = Suppliers.memoize(() ->
transitions.stream().filter((t) ->
(t.isObservable() == true)).collect(Collectors.toSet()));
}
public getObservables() {
return observables.get();
}
}
问题:
- 是否正确?
- 如果转换改变了其可观察性,此信息是否也会传播到供应商?
抱歉我的英语不好,我希望你已经足够清楚了。
- 是的,没错。
不,您将在转换中所做的更改不会自动传播。对于这种情况,供应商 AFAIK 不适合。 要么你需要像这里一样手动覆盖它:
public void invalidate(){ memorized = Suppliers.memoize(supplier); }
如果您知道您的更新不会那么频繁并且不需要可靠的读取,
memoizeWithExpiration
也可以使用。或者您只需要使用
Cache
,例如:CacheLoader<Key, Graph> loader = new CacheLoader<Key, Graph>() { public Graph load(Key key) throws AnyException { return createExpensiveGraph(key); } }; LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder().build(loader);