Guest User

Untitled

a guest
Jul 20th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. import scala.concurrent.stm._
  2.  
  3. val x = Ref(0) // allocate a Ref[Int]
  4. val y = Ref.make[String]() // type-specific default
  5. val z = x.single // Ref.View[Int]
  6.  
  7. atomic { implicit txn =>
  8. val i = x() // read
  9. y() = "x was " + i // write
  10. val eq = atomic { implicit txn => // nested atomic
  11. x() == z() // both Ref and Ref.View can be used inside atomic
  12. }
  13. assert(eq)
  14. y.set(y.get + ", long-form access")
  15. }
  16.  
  17. // only Ref.View can be used outside atomic
  18. println("y was '" + y.single() + "'")
  19. println("z was " + z())
  20.  
  21. atomic { implicit txn =>
  22. y() = y() + ", first alternative"
  23. if (x getWith { _ > 0 }) // read via a function
  24. retry // try alternatives or block
  25. } orAtomic { implicit txn =>
  26. y() = y() + ", second alternative"
  27. }
  28.  
  29. val prev = z.swap(10) // atomic swap
  30. val success = z.compareAndSet(10, 11) // atomic compare-and-set
  31. z.transform { _ max 20 } // atomic transformation
  32. val pre = y.single.getAndTransform { _.toUpperCase }
  33. val post = y.single.transformAndGet { _.filterNot { _ == ' ' } }
Add Comment
Please, Sign In to add comment