Search code examples
javaguavagoogle-guava-cache

Cache filter on collection with Guava


I'm developing a program that performs some operations on automatas. An automata is made up of states (aka node) and transitions (aka edges) and I need to filter them to retrieve set with particular properties. This operation is easy to implement, but it is performed several times and I would write a little cache on it.

In the fragment of code below there is my implementation and I'd like to know if is the correct way to filter and memoize the observable transitions.

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

Questions:

  1. Is it correct?
  2. If a transition changes its observability is this information propagate also to the Supplier?

I'm sorry for my poor English, i hope that is enough clear.


Solution

    1. Yes, it's correct.
    2. No, changes you will do in transitions won't automatically be propagated. And for this case Supplier AFAIK not suitable. Either you need to overwrite it manually like here:

      public void invalidate(){
          memorized = Suppliers.memoize(supplier);
      }
      

      Also memoizeWithExpiration will work if you know that your update will be not so frequent and you don't need reliable reads.

      Or you just need to use Cache, for example:

      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);