views:

20

answers:

0

I am caching objects that are being sent to my component in an asynchronous way. In other words, the order in which these objects arrive is unpredictable. To avoid any issues, I have included a version attribute to my objects (which basically is a timestamp). The idea is that any object that arrives with a version that's older than the one that has already been cached, it can be discarded.

The "Element" class of EHCache (which wraps objects in an EHCache) seems to facilitate this: apart from a key and value, the constructor can take a (long-based) version. I cannot make this work in the way I'd expect it to work though. 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'd expect the code above to cause the cached value to be "NEW", instead, "OLD" is printed. If you play a bit with the order in which elements are inserted, you'll find that the last one that has been inserted is the one that will remain in cache. Versioning seems to be ignored.

Am I not using the versioning-feature properly, or is it perhaps not intended to be used for this purpose? Can anyone recommend alternatives?