简体   繁体   中英

singleton class behaviour when calling from independent java classes

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 ?

我认为只要在声明时而不是在构造函数中初始化缓存映射,问题就会解决。

private static HashMap<String,Object> cacheMap = new HashMap<String,Object>();

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;

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