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调整为指向新数据.