Search code examples
javacachingdictionarytuplescomputation

Java: Data structure for caching computation result?


I have an expensive computation, the result of which I'd like to cache. Is there some way to make a map with two keys? I'm thinking of something like Map<(Thing1, Thing2), Integer>.

Then I could check:

if (! cache.contains(thing1, thing2)) {
  return computeResult();
}
else {
  return cache.getValue(thing1, thing2);
}

pseudocode. But something along those lines.


Solution

  • You need to create a class that holds Thing1 and Thing2, e.g:

    class Things {
        public final Thing1 thing1;
        public final Thing2 thing2;
        public Things(Thing1 thing1, Thing2 thing2) {
          this.thing1 = thing1; 
          this.thing2 = thing2;
        }
        @Override
        public boolean equals(Object obj) { ... }
        @Override
        public int hashCode() { ... };
     }
    

    Then to use it:

    Things key = new Things(thing1, thing2);
    if (!cache.contains(key) {
        Integer result = computeResult();
        cache.put(key, result);
        return result;
    } else {
        return cache.getValue(key);
    }
    

    Note you have to implement equals and hashcode to make this code work properly. If you need this code to be thread-safe then have a look at ConcurrentHashMap.