Scala pattern matching in a concurrent program

Viewed 272

I'm new to Scala, and I want to write some multi-threaded code with pattern matching, and I was wondering if I could treat the pattern-matching code as atomic.

For example:

abstract class MyPoint
case class OneDim(x : Int) extends MyPoint
case class TwoDim(x : Int, y : Int) extends MyPoint

var global_point : MyPoint = new OneDim(7)

spawn {
    Thread.sleep(scala.util.Random.nextInt(100))
    global_point = new TwoDim(3, 9)
}
Thread.sleep(scala.util.Random.nextInt(100))

match global_point {
    case TwoDim(_, _) => println("Two Dim")
    case OneDim(_) => println("One Dim")
}

Is it possible that the execution will go as the following:

  1. The main thread reaches the "match global_point" code, finds out that *global_point* is not of type TwoDim and pauses (returns to the scheduler).
  2. The spawned thread changes *global_point* to be of type TwoDim
  3. The main thread returns, finds out that the *global_point* is not of type OneDim, thinks there are no matches to *global_point* and raises a NoMatch exception.

Is this kind of execution avoided internally by Scala? If it does, then how? Does the matching take a snapshot of the object and then try to match it against the patterns? Is there a limit to the snapshot depth (the match patterns can be complex and nested)?

3 Answers
Related