Advertisement
Guest User

Untitled

a guest
Dec 21st, 2014
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1.  
  2. import scala.collection._
  3. import scala.concurrent._
  4. import ExecutionContext.global
  5.  
  6. object Ex1 {
  7. var x: List[Int] = null
  8. def foo() {
  9. val buffer = mutable.ListBuffer[Int]()
  10. buffer ++= (0 until 100)
  11. x = buffer.result
  12. Future {
  13. // not safe!
  14. // a non-immutable object is assigned to a non-final field
  15. println(x)
  16. }
  17. }
  18. }
  19.  
  20. object Ex2 {
  21. val buffer = mutable.ListBuffer[Int]()
  22. buffer ++= (0 until 100)
  23. val x = buffer.result
  24. Future {
  25. // again not safe!
  26. // the reference to `Ex2.this` escaped to another thread during construction
  27. // so it does not matter that the field `x` is final
  28. println(x)
  29. }
  30. }
  31.  
  32. class Ex3 {
  33. val buffer = mutable.ListBuffer[Int]()
  34. buffer ++= (0 until 100)
  35. val x = buffer.result
  36. }
  37.  
  38. object Test extends App {
  39. val obj = new Ex3
  40. Future {
  41. // safe!
  42. // although the list is itself not an immutable object,
  43. // it is obtained by reading a final field in an immutable object `Ex3`,
  44. // so any modifications to the list prior to assignment to the field `x` become visible,
  45. // and the assignment of `x` cannot be reordered with the assignment to the field `obj`
  46. // (see Goetz book, page 350)
  47. obj.x
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement