与以下链接相同,我与提问者使用相同的代码。
Java multi-threading atomic reference assignment
在我的代码中,有
HashMap<String,String> cache = new HashMap<String,String>();
public class myClass {
private HashMap<String,String> cache = null;
public void init() {
refreshCache();
}
// this method can be called occasionally to update the cache.
//Only one threading will get to this code.
public void refreshCache() {
HashMap<String,String> newcache = new HashMap<String,String>();
// code to fill up the new cache
// and then finally
cache = newcache; //assign the old cache to the new one in Atomic way
}
//Many threads will run this code
public void getCache(Object key) {
ob = cache.get(key)
//do something
}
}
我一遍又一遍地阅读sjlee的答案,我不明白在什么情况下这些代码会出错。谁能给我举个例子吗?
请记住,我不关心 getCache 函数是否会获取旧数据。
很抱歉我无法对上述问题添加评论,因为我没有 50 声望。
所以我只是添加一个新问题。
最佳答案
如果没有内存障碍,您可能会看到 null
或旧 map ,但您可能会看到不完整的 map 。 IE。你会看到其中的一部分,但不是全部。因此,如果您不介意条目丢失,那么这不是问题,但您可能会看到 Map 对象,但看不到它所引用的任何内容,从而导致可能的 NPE。
无法保证您会看到完整的 map 。
final
字段将可见,但非 Final 字段可能不可见。
关于Java多线程原子赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25473315/