Guest User

Untitled

a guest
Jan 22nd, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. // Does the Java memory model guarantee that this program will *always* print
  2. // x=1 and y=2
  3. //
  4. //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
  5. // y is volatile and nor are they modified within a sychronized block (or within the confines of a j.u.c Lock)?
  6. // i.e. I am unsure whether you can observe
  7. // x=0 and y=0
  8.  
  9. //
  10. //I believe that the memory model *definitely makes the guarantee* that t1 will *never* print something like:
  11. // x=0 and y=2
  12. //
  13.  
  14. object HB extends App {
  15. @volatile var v = true
  16. var x = 0
  17. var y = 0
  18.  
  19. val t1 = new Thread {
  20. override def run(): Unit = {
  21. while (v) {
  22. Thread.sleep(10L)
  23. }
  24. println(s"x=$x and y=$y")
  25. }
  26. }
  27.  
  28.  
  29. val t2: Thread = new Thread {
  30. override def run(): Unit = {
  31. x = 1
  32. y = 2
  33. v = false
  34. }
  35. }
  36. t1.start()
  37. t2.start()
  38. t1.join()
  39. t2.join()
  40. }
Add Comment
Please, Sign In to add comment