Can same Ehcache object of same CacheManager be us

2019-05-31 04:26发布

问题:

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?