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 开发者_如何学Cthe best-practise data structure to be used is also sufficient...
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.
Make a hashtable where the value is a reference to the object, so that you don't have to store the object multiple times if it has multiple keys.
Luckily, this is the default in Java.
Just use plain MultiKeyMap or even decorate LRU map:
MultiKeyMap cache = MultiKeyMap.decorate(new LRUMap());
cache.put(keyA, keyB, value);
精彩评论