简体   繁体   中英

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

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.

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM