gpt4 book ai didi

java - 更改 Map 的值是原子操作吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:45:37 24 4
gpt4 key购买 nike

我想知道是否需要同步或使用并发类,或者相反,如果对 map 的唯一修改正在改变,那么在多线程环境中使用非并发类并且不对 map 进行同步是否线程安全 map 的值。

我问这个的原因是 HashMap(和其他非并发映射文档)有这样的评论:

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map.

这让我相信,如果修改不是结构性的(即没有添加或删除),我应该能够在没有同步的情况下更新(非并发) map 。

我读的对吗?即更新映射中的值是一个原子过程吗?

最佳答案

更新映射值不是一个原子过程。但是,让多个不同的线程各自尝试并发修改映射值不会导致非常奇怪的异常或由于并发错误而导致的错误。例如,您不会导致其中一个键/值对消失,或从 map 中删除随机元素。

然而,一个线程在更新键/值对时所做的更新不一定对其他线程可见,除非有一些其他的同步正在进行(例如,如果值是 AtomicIntegers)。最重要的是,甚至无法保证线程会看到自己的更新,因为它们可能会被其他线程破坏。

希望这对您有所帮助!

关于java - 更改 Map 的值是原子操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9659015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com