Skip to content

Instantly share code, notes, and snippets.

@oxbowlakes
Last active January 12, 2018 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oxbowlakes/977ad3e4f65d0b99d4cf30f040cbc272 to your computer and use it in GitHub Desktop.
Save oxbowlakes/977ad3e4f65d0b99d4cf30f040cbc272 to your computer and use it in GitHub Desktop.
// Does the Java memory model guarantee that this program will *always* print
// x=1 and y=2
//
//Or might the JVM decide that the changes made to x and y in t2 do not need to be visible from t1 because neither x nor
// y is volatile and nor are they modified within a sychronized block (or within the confines of a j.u.c Lock)?
// i.e. I am unsure whether you can observe
// x=0 and y=0
//
//I believe that the memory model *definitely makes the guarantee* that t1 will *never* print something like:
// x=0 and y=2
//
object HB extends App {
@volatile var v = true
var x = 0
var y = 0
val t1 = new Thread {
override def run(): Unit = {
while (v) {
Thread.sleep(10L)
}
println(s"x=$x and y=$y")
}
}
val t2: Thread = new Thread {
override def run(): Unit = {
x = 1
y = 2
v = false
}
}
t1.start()
t2.start()
t1.join()
t2.join()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment