Can this use case ever be developed in ehcache?

I want to use ehcache not only as a cache, but also as a container with dirty objects that I want to dump into my database when the objects are evicted / expired. during normal processing, I use the key to search in ehcache. if the key is missing, I read the data from the database and put it in ehcache. the value is actually a complex object that I am modifying. when the ttl / idle time / overflow condition occurs, I see that the called CacheEventListener calls are called. but there is a big problem. notifyElementExpired is called after the key-value is removed from the cache. therefore there is a race condition. if I perform the task of dumping a dirty value into the cache in notifyElementExpired and at the same time, in a different thread, reading for the same key occurs, then there is a synchronization problem.The 2nd thread will not find the object in ehcache and therefore will go to the database while the other thread is still ready for the thread.

I tried experimenting with ehcache with the record, and I don't think this works either.

is there a solution here

I would really appreciate good solutions to this problem, even if it is related to a different caching mechanism than ehcache.

thank

+5
source share
1 answer

If you're ok with the cache in memory, I would suggest extending the Google Guava CacheLoader library, for example:

public class DBLoader extends CacheLoader<String, String> {

    @Override
    public String load(String key) throws Exception {
        // load a value from the database
        return value;
    }
}

Then in use something like:

private LoadingCache<String, String> dbCache = CacheBuilder.newBuilder()
.expireAfterWrite(CACHE_EXPIRE_IN_SECONDS, TimeUnit.SECONDS)
.build(new DBLoader());

String value = dbCache.get(someKey);


Of course, you will need to carefully select the correct exception handling.

I find guava much easier than setting up ehcache properly.

+1
source

All Articles