Quantcast
Viewing all articles
Browse latest Browse all 1367

State inside of flow operators?

@ignatius wrote:

Is mutable state allowed inside of flow operators, as long as the state does not escape the operator?

  Source(1 to 100)
      .async // let's introduce threat-safety issues
      .map {
        var mutableNumber = 0 // mutated whenever an element is received
        item => {
          mutableNumber += item // non-atomic operation
          mutableNumber
        }
      }
      .runForeach(println)

I tried as hard as I could to create a race condition using async and Thread.sleep in-between operations, but it appeared impossible - which would be great. As I understand it, operators run inside of actors, so I presume they provide the same single-threaded illusion. Here is an example of such an attempt to create a race condition:

  Source(1 to 100)
      .async
      .map {
        @volatile var mustBeFalse = false
        item => {
          if (mustBeFalse) {
            // this never happens
            println("Oh no, race condition.")
            throw new IllegalStateException()
          }
          mustBeFalse = true
          Thread.sleep(20)
          mustBeFalse = false
          item
        }
      }
      .async // just in case
      .runForeach(println)

Posts: 2

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 1367

Trending Articles