java hashmap同步问题_java – 同步不经常更新的hashmap的最佳方法

At the point where I do myMap = myLocalMap, is there a possibility

that some other thread that is reading data from myMap get an empty or

unexpected result?

不,那里没有.为参考变量读取和写入are atomic,这意味着整个操作一次全部发生,并且在整个操作完成之前,结果对其他线程不可见.因此,从’myMap’读取的任何线程都将获得旧的myMap或新的myMap,但永远不会得到空的或不一致的结果.此外,在’myMap’上使用volatile关键字意味着所有线程始终都会知道新数据:如果myMap已更新,则在更新操作启动后启动的任何读取操作都将使用该更新值.

来自Oracle Java教程的支持文档:

Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).

any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable

If a variable is declared with the volatile keyword then it is

guaranteed that any thread that reads the field will see the most

recently written value.

同样来自Vogella的同一篇文章:

The Java language specification guarantees that reading or writing a

variable is an atomic operation

另请参阅this参考,特别是“清单3.使用volatile变量进行安全的一次性发布”,其中描述了与您的非常类似的场景.

顺便说一下,我同意Giovanni关于ConcurrentHashMap的观点.但在您的情况下,您不需要使用ConcurrentHashMap,因为所有更新都发生在单个事务中,而您只是将Map调整为指向新数据.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值