Skip to content

Instantly share code, notes, and snippets.

@axel22
Last active August 29, 2015 14:11
Show Gist options
  • Save axel22/9f04fb25292ad07e946d to your computer and use it in GitHub Desktop.
Save axel22/9f04fb25292ad07e946d to your computer and use it in GitHub Desktop.
Snippets showing several publication examples.
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)
Future {
// not safe!
// a non-immutable object is assigned to a non-final field
println(x)
}
x = buffer.result
}
}
object Ex2 {
val buffer = mutable.ListBuffer[Int]()
buffer ++= (0 until 100)
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(Ex2.x)
}
val x = buffer.result
}
class Ex3 {
val buffer = mutable.ListBuffer[Int]()
buffer ++= (0 until 100)
val x = buffer.result
}
class Ex3Holder {
val obj = new Ex3
}
object Test extends App {
var holder: Ex3Holder = null
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)
holder.obj.x
}
holder = new Ex3Holder
}
// bottom line: just use synchronized
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment