Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Often the considerations surrounding concurrency focus on erroneous changes to state or on deadlocks. But visibility of state from different threads is equally important. There are many places in a modern computer where state can be cached. In registers, L1 cache on the processor, L2 cache between the processor and memory, etc. JIT compilers and the Java memory model are designed to take advantage of caching whenever possible or legal, because it can speed things up.</p> <p>It can also give unexpected and counterintuitive results. I believe that is happening in this case.</p> <p>When an instance of B is created, the instance variable x is briefly set to 0 before being set to whatever value was passed to the constructor. In this case, 1. If another thread tries to read the value of x, it could see the value 0 even if x has already been set to 1. It could be seeing a stale, cached value.</p> <p>To ensure that the up-to-date value of x is seen, there are several things you can do. You could make x volatile, or you could protect the read of x with synchronization on the B instance (for example, by adding a <code>synchronized getX()</code> method). You could even change x from an int to a <code>java.util.concurrent.atomic.AtomicInteger</code>.</p> <p>But by far the simplest way to correct the problem is to make x final. It is never going to change during the lifetime of B anyway. Java makes special guarantees for final fields, and one of them is that after the constructor completes, a final field set in the constructor will be visible to any other thread. That is, no other thread will see a stale value for that field.</p> <p>Making fields immutable has many other benefits as well, but this is a great one.</p> <p>See also <a href="http://jeremymanson.blogspot.com/2007/08/atomicity-visibility-and-ordering.html" rel="nofollow">Atomicity, Visibility, and Ordering</a> by Jeremy Manson. Particularly the part where he says:</p> <blockquote>(Note: when I say synchronization in this post, I don't actually mean locking. I mean anything that guarantees visibility or ordering in Java. This can include final and volatile fields, as well as class initialization and thread starts and joins and all sorts of other good stuff.)</blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload