【发布时间】:2013-05-14 03:28:44
【问题描述】:
书里有下面的例子,它只同步insert,没有同步lookup。我知道currentIndex在insert之后会指向不同的对象,但是指向不同对象的操作是原子的?例如,假设指针是 8 字节(在 64 位机器上),那么 currentIndex 会在某些时候切换指针,但如果该切换不是原子的,例如它首先切换前 4 个字节,然后切换第二个 4字节,如果在第一次和第二次切换之间,我们查找数据,那么指向对象的指针永远不存在,这将导致问题
class ImmutableService[Key, Value] extends Service[Key, Value] {
var currentIndex = new ImmutableHashMap[Key,Value]
def lookUp(k: Key): Option[Value] = currentIndex.get(k)
def insert(k: Key, v: Value): Unit = synchronized {
currentIndex = currentIndex + ((k, v))
}
}
【问题讨论】:
-
从stackoverflow.com/questions/4756536/… 和其他地方,所有分配都被认为是原子的。
标签: scala concurrency atomic immutability