Reputation: 134
This question may be a very basic.But wanted to get clarified. My requirement is to create a simple cache to store and retrieve the values across my application.So I created a singleton java class having hashmap to store and retrieve the values.
public class CacheUtil {
private static HashMap<String,Object> cacheMap = null;
private static CacheUtil appCache =null;
private CacheUtil() {
cacheMap = new HashMap<String,Object>();
}
public static synchronized CacheUtil getInstance() {
if(appCache == null) {
appCache = new CacheUtil();
}
return appCache;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public void setFields(String key,HashMap<String,String> map) {
cacheMap.put(key, map);
}
public HashMap<String,String> getFields(String key) {
return (HashMap<String, String>) cacheMap.get(key);
}
}
Also I have 2 independent java classes class1.java & class2.java.
class1.java is setting in to cache
CacheUtil cache = CacheUtil.getInstance();
cache.setFields("key1",value);
Once the class1 is set the class2 is trying to retrieve
CacheUtil cache = CacheUtil.getInstance();
cache.getFields("key1");
At this point of time the cache object is different(checked by toString() method on the object) So I am always getting the null for key1 in class2.java.
So would like to know what is the reason i am getting 2 different objects even though its declared as singleton with the static modifier ?
Upvotes: 1
Views: 326
Reputation: 1661
I think problem will resolve simply if you initialize cache map at declaration time rather than in constructor.
private static HashMap<String,Object> cacheMap = new HashMap<String,Object>();
Upvotes: 2
Reputation: 29
Are you sure there is not another thread that override the "key1" value?
Try eager init. The instance of Singleton Class is created at the time of class loading:
private static final CacheUtil instance = new CacheUtil();
private CacheUtil(){}
public static CacheUtil getInstance(){
return instance;
}
and remove static keyword to cacheMap:
private Map<String, Object> cacheMap;
Upvotes: 1