Search code examples
javacaching

cache with multiple keys


I am looking out for implementing a timestamp based cache with multiple keys. What data structure other than hash tables I would use. Any suggestions...

for two values, pair could be used, java (un)fortunately doesn't have a pair.

if it has to be triplet or quartet, what architecture is advised. or just the best-practise data structure to be used is also sufficient...


Solution

  • Assuming that you want to only retrieve the cached value given all of the keys, you can simply just make a CacheKey object. Maps/Hashtable are still a decent candidate here:

    map.put(new CacheKey(keyA, keyB, keyC), value);
    map.get(new CacheKey(keyA, keyB, keyC));
    //etc...
    

    Just make sure to properly implement equals() and hashcode() in the CacheKey class.

    However if you intend to heavily use this map or hashtable as a cache, you should seriously consider re-using an existing caching library, unless you want to deal with things like limiting the number of entries stored in the map, choosing which entries get evicted when you reach the limit, etc. EhCache is incredibly simple to use and has many many configuration options - caches can have a maximum number of entries or maximum memory size, caches can overflow to disk, etc.