Happens-before relationships with volatile fields and synchronized blocks in Java – and their impact on non-volatile variables?

Yes, it is guaranteed that thread 2 will print “done” . Of course, that is if the write to b in Thread 1 actually happens before the read from b in Thread 2, rather than happening at the same time, or earlier!

The heart of the reasoning here is the happens-before relationship. Multithreaded program executions are seen as being made of events. Events can be related by happens-before relationships, which say that one event happens before another. Even if two events are not directly related, if you can trace a chain of happens-before relationships from one event to another, then you can say that one happens before the other.

In your case, you have the following events:

  • Thread 1 writes to s
  • Thread 1 writes to b
  • Thread 2 reads from b
  • Thread 2 reads from s

And the following rules come into play:

  • “If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).” (the program order rule)
  • “A write to a volatile field (ยง8.3.1.4) happens-before every subsequent read of that field.” (the volatile rule)

The following happens-before relationships therefore exist:

  • Thread 1 writes to s happens before Thread 1 writes to b (program order rule)
  • Thread 1 writes to b happens before Thread 2 reads from b (volatile rule)
  • Thread 2 reads from b happens before Thread 2 reads from s (program order rule)

If you follow that chain, you can see that as a result:

  • Thread 1 writes to s happens before Thread 2 reads from s

Leave a Comment