【问题标题】:Immutable collection (an example in book of scala in depth)不可变集合(scala 深度书中的一个例子)
【发布时间】: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))
   }
}

【问题讨论】:

标签: scala concurrency atomic immutability


【解决方案1】:

是的,currentIndex 是一个引用 - 所以对它的更改将自动完成。

检查:

Are 64 bit assignments in Java atomic on a 32 bit machine?

【讨论】:

    猜你喜欢
    • 2012-01-07
    • 2011-01-25
    • 1970-01-01
    • 2013-08-30
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    相关资源
    最近更新 更多