public class MemoryCard {
private static Map<String, AccountCache> caches = new HashMap<String, AccountCache>(); /**
 * 存入缓存
 * @param key
 * @param cache
 */
public void putCache(String key, AccountCache accountCache) {
caches.put(key, accountCache);
}
/**
 * 获取对应缓存
 * @param key
 * @return
 */
public AccountCache getCacheByKey(String key) {
if (caches.containsKey(key)) {
return caches.get(key);
}
return null;
}
}
这是写的缓存类,定时器没过30秒去数据库查询数据,再调用putCache方法,但是测试的时候发现比如有两个map值,
key1的value是value1,key2的value是value2,但是后面getCacheByKey取值的时候,取到key1的value是value1,key2的value是value1,死活找不出原因了

解决方案 »

  1.   

    看看两次调getCacheByKey的时候,是不是用同一个变量接受了。
    类似于AccountCache ac = getCacheByKey("key1");
    putCache("key1", ac);
    ac = getCacheByKey("key1");
    putCache("key2", ac);
      

  2.   


    AccountCache ac = getCacheByKey("key1");
    putCache("key1", ac);
    ac = getCacheByKey("key2");
    putCache("key2", ac);
      

  3.   

    你在取值的时候做一下判断: for (String key : caches.keySet()) {
    if (key.equals("key1")) {
    String  value1 = caches.get(key1).toString();}
    if (key.equals("key2")) {
    String  value2 = caches.get(key2).toString();}
    }
      

  4.   

    HashMap是非线程安全类,从你的描述来看,这个map是多线程可见的对象,自然需要考虑线程安全的问题
      

  5.   

    5楼正解,建议用ConcurrentHashMap