So here is the problem I am trying to solve - I have an Object with two integer fields that I want to cache
public class MyObject {
int x;
int y;
....
}
Now the field x
is what I mainly match on - but there can be duplicates in which case I want to fall back on the second field (so that this.x=that.x and this.y=that.y). y can only be 25 distinct values. Now I know I could just combine the two as a String and use that as the cache key, but then I would have to try x+[25 possible values]
to actually determine if it was not in the cache - making cache misses very expensive. I was thinking of trying to store a List<Integer>
as the cache value for the field x
and then if their was more then one, iterate down the list and look for a match on y
.
Now if I use a ConcurrentList
(or a Set if I care about duplicates - lets ignore that for now) will multiple threads be able to add to it and then put it back into the cache without race conditions? Is it possible that Ehcache might return two different List Objects to two threads and then when they add their new value to the list and attempt to put it back to the cache I could get undeterministic results? Do you see a better way of constructing this cache?
EDIT : I appreciate the answers below, but everyone seems to be missing the main point. Will this work? Could Ehcache actually return two different objects for the same cacheKey (say if the object was on disk during the call and it's serialized it twice, once for each call).