Another question from Learning Concurrent Programming in Scala - Second Edition (Search | Packt Subscription)
Is this statement true:
“When writing to a volatile var, then that write and all previous writes in that thread are guaranteed visible to other threads.”
I’ve derived that from…
object Volatile extends App {
case class Page(txt: String, var position: Int)
def thread(body: =>Unit): Thread = {
val t = new Thread {
override def run() = body
}
t.start()
t
}
val pages = for (i <- 1 to 5) yield
new Page("Na" * (100 - 20 * i) + " Batman!", -1)
@volatile var found = false
for (p <- pages) yield thread {
var i = 0
while (i < p.txt.length && !found)
if (p.txt(i) == '!') {
p.position = i
found = true
} else i += 1
}
while (!found) {}
log(s"results: ${pages.map(_.position)}")
}
and some of the associated text…
Note that a write to position occurs before the write to found in the spawned threads, which in turn occurs before reading found in the main thread. This means that the main thread always sees the write of the thread that set found, and hence prints at least one position other than -1.
I had assumed that volatile was a per var before reading this and I just wanted to check that I understood it correctly.