我正在开发一个在自动机上执行一些操作的程序。自动机由状态(又名节点)和转换(又名边缘)组成,我需要过滤它们以检索具有特定属性的集合。这个操作很容易实现,但是执行了好几次,我会在上面写一点缓存。
下面的代码片段是我的实现,我想知道过滤和内存可观察转换是否是正确的方法。
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);
关于java - 使用 Guava 对集合进行缓存过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36056616/