1

In the book, it has the following example, it only sync the insert, but didn't sync lookup.I knew the currentIndex will point to a different object after insert, but is the operation of pointing to a different object atomic? example, suppose the pointer is of 8 bytes (on 64 bit machine), then at some point currentIndex will switch the pointer, but if that switch is not atomic, such as it first switch the first 4 bytes, and then switch the second 4 bytes, and if between the first and second switch, we lookup the data, then the pointer points to an object never exists and that will cause problem

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))
   }
}
4

1 回答 1

0

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

查看:

Java 中的 64 位分配在 32 位机器上是原子的吗?

于 2013-06-07T23:59:19.643 回答