Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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()
- }
Add Comment
Please, Sign In to add comment