Skip to content
Playground(another site)

bynk.par.store_write_in_closure

Error A closure passed to parForEach, parTraverse, parTraverseAll or parTraverseTry writes a store field (put, remove, update, upsert, add, append or :=). Its branches run concurrently, and a get then a put across them loses updates, so store writes stay sequential, as they do in a par { … } block.

The closure given to parForEach, parTraverse, parTraverseAll or parTraverseTry runs once per element, all at once, so it may not write a store field, which is the rule a par { … } block already follows. Every <- is an await point, so a get then a put in the closure lets the other branches write in between, and their updates are lost. A single call such as update is atomic per key, but it is refused here too, so the two rules stay equal. Run the loop with forEach (or traverseAll / traverseTry), where each element finishes before the next starts, so a single-call update stays atomic. A store write reads the entry before it stages the write, so the sequential form reads one entry at a time; per-key atomicity is the reason for the rule. To keep the concurrent part, collect with parTraverseAll and write afterwards.

Example

xs.parForEach((x: Int) => {
let o <- counts.get("k")
counts.put("k", o.getOrElse(0) + 1) // ✗ two increments of three are lost
})
xs.forEach((x: Int) => counts.update("k", (v) => v + 1)) // ✓ sequential and atomic per key

In the Book

See also

  • Every code in its category, Other, on the diagnostic index.
  • bynk explain bynk.par.store_write_in_closure shows the same from the installed toolchain, without a network.