Can same Ehcache object of same CacheManager be us

2019-05-31 04:05发布

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.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-05-31 04:42

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?

查看更多
做自己的国王
3楼-- · 2019-05-31 04:55

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?

查看更多
登录 后发表回答