簡體   English   中英

使用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();
    }
}

問題:

  1. 這是正確的嗎?
  2. 如果過渡改變了其可觀察性,該信息是否還會傳播到供應商?

我為我的英語不好對不起,我希望這足夠清楚。

  1. 是的,這是正確的。
  2. 不,您在轉換中所做的更改不會自動傳播。 在這種情況下,供應商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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM