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?
来源:https://stackoverflow.com/questions/45834377/can-same-ehcache-object-of-same-cachemanager-be-used-by-multiple-threads