Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import scala.collection._
- import scala.concurrent._
- import ExecutionContext.global
- object Ex1 {
- var x: List[Int] = null
- def foo() {
- val buffer = mutable.ListBuffer[Int]()
- buffer ++= (0 until 100)
- x = buffer.result
- Future {
- // not safe!
- // a non-immutable object is assigned to a non-final field
- println(x)
- }
- }
- }
- object Ex2 {
- val buffer = mutable.ListBuffer[Int]()
- buffer ++= (0 until 100)
- val x = buffer.result
- Future {
- // again not safe!
- // the reference to `Ex2.this` escaped to another thread during construction
- // so it does not matter that the field `x` is final
- println(x)
- }
- }
- class Ex3 {
- val buffer = mutable.ListBuffer[Int]()
- buffer ++= (0 until 100)
- val x = buffer.result
- }
- object Test extends App {
- val obj = new Ex3
- Future {
- // safe!
- // although the list is itself not an immutable object,
- // it is obtained by reading a final field in an immutable object `Ex3`,
- // so any modifications to the list prior to assignment to the field `x` become visible,
- // and the assignment of `x` cannot be reordered with the assignment to the field `obj`
- // (see Goetz book, page 350)
- obj.x
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement