Can same Ehcache object of same CacheManager be used by multiple threads?

十年热恋 提交于 2019-12-08 07:56:09

问题


I have created a Cache object which stores a String as the key and a serialized object as the value.

Cache(String--->Object) 

I am trying to run three Akka threads which retrieve and write into the same Ehcache object in a synchronized way.

Thread 1- synchronized (LockForEhcache){ 
              serializedObj = cachename.get("key"); //--- this returns an Object            
          }
          //modify the serializedObj here....
          //Again store the modify Object in the Cache
          synchronized (LockForEhcache){
              cachename.clear();
              cachename.put("key",serializedObj);
Thread 2- synchronized (LockForEhcache){ 
              serializedObj = cachename.get("key"); //--- this returns null
          }
Thread 3- synchronized (LockForEhcache){ 
              serializedObj = cachename.get("key"); //--- this returns null
          }

But only one thread gets the value stored in the Cache. For the rest of the threads, it throws a NullPointerException. I can't figure out why.


回答1:


First of all, a cache is not a store. So you can't expect a cache to return the latest data all the time. For different reasons, it might return null.

Right now, unless some eviction or expiration occurs, the data should be there. So I will need a full example to tell you what's going on.

My first question would be: Why do you clear and put? Why not only put? And do we agree that clear will clear all entries? You only have one entry in your cache?




回答2:


I'm only seeing now that the first thread also starts with a get, so does that mean that the mapping is installed always? If so, are you sure the other threads are actually using the same Cache instance?



来源:https://stackoverflow.com/questions/45834377/can-same-ehcache-object-of-same-cachemanager-be-used-by-multiple-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!