I cache objects that are sent to my component asynchronously. In other words, the order in which these objects arrive is unpredictable. To avoid any problems, I included the version attribute in my objects (basically this is a timestamp). The idea is that any object that comes with a version that is older than the one that has already been cached can be discarded.
The Element class of the EHCache class (which wraps objects in EHCache) seems to make this easier: in addition to the key and value, the constructor can take a (long) version. I cannot do this work as I expected it to work. The following code snippet demonstrates my problem (using EHCache 2.1.1):
public static void main(String[] args) { final CacheManager manager = CacheManager.create(); final Cache testCache = new Cache(new CacheConfiguration("test", 40)); manager.addCache(testCache); final String key = "key"; final Element elNew = new Element(key, "NEW", 2L); testCache.put(elNew); final Element elOld = new Element(key, "OLD", 1L); testCache.put(elOld); System.out.println("Cache content:"); for (Object k : testCache.getKeys()) { System.out.println(testCache.get(k)); } }
I expect the code above will cause the cached value to be "NEW", instead printed "OLD". If you play around a bit with the order in which the elements are inserted, you will find that the last one that was inserted is the one that remains in the cache. Versions seem to be ignored.
Am I using the version control function correctly, or maybe not designed for this purpose? Can anyone recommend alternatives?
source share