Search code examples
scalafrpreactive

How does Scala manage to avoid racing in reactive programming?


As I have realized up until right now the basic idea for functional reactive programming in Scala is to define a signal that extends the DynamicVariable class of Scala but I could not understand something written in explanation of that class it said:

DynamicVariables provide a binding mechanism where the current value is found through dynamic scope, but where access to the variable itself is resolved through static scope.

If I am not wrong, the dynamic scope is when a called function sees a variable from the scope of the caller program and the static scope is when it sees a variable from its own scope like the pseudo-code that follows:

    let x = 1
    func dynamic (y: Int) = y + x
    func static (w: Int) = y + x
    func main() = {
        let x = 2  
        dynamic (3)  //returns 5
        static (3)   //returns 4
    }

So the question is how is the meaning of accessing the variable itself, and if it implies writing to it, how Scala prevent racing when some functions have each a copy and want to write to the variable?


Solution

  • In the following, dv1 is defined in the normal fashion, and is only accessible through the usual scope rules. The function checkDv1 sees dv1 because dv1 is defined in its scope.

    val dv1: DynamicVariable[Int] = new DynamicVariable(42)
    
    def checkDv1 = println( dv1.value )
    

    However, when checkDv1 is invoked inside the withValue() dynamic scope, the value it gets back is different, as in it will be the newly bound value.

    def testDv = dv1.withValue(41) {
      checkDv1
    }
    
    checkDv1
    testDv
    checkDv1
    

    So, the output from those three function invocations should be:

    42
    41
    42
    

    as the dynamic scope changes.

    For your other question, a DynamicVariable has a binding within the context of a thread. When a new thread is created, the current binding is copied to the new thread, and they have no further interaction with each other. Hence, no race conditions.

    DynamicVariable has very little to do with reactive programming, except that its behavior is well defined in a multi-threaded environment.