@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
andThread.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