Java多线程原子赋值

标签 java multithreading

与以下链接相同,我与提问者使用相同的代码。
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/

相关文章:

java - 应用程序部署后无法访问服务器

java - 为什么 "smallest"不返回任何内容?

java - <h :commandButton> doesn't start the action - NO IDEA?

c# - 多线程列表模式建议

java - 哈希表、ConcurrentHashMap 和数据可见性

java - 对 Android 应用程序进行压力测试

java - 在 java 中使用单独的测试项目的 Scala 的代码覆盖率

C# 在主线程关联中执行 Threading.ThreadPool.QueueUserWorkItem 回调

multithreading - 在 amd64 上拆分堆栈是不必要的

java - 使用我的 JFrame 同时播放音乐