In Java, does locking ensure correct order of reads and write to nonvolatile locations <p>Suppose I have a shared object of class:</p> <pre><code>class Shared { private int x = 0 ; private int y = 0 ; private Semaphore s = new Semaphore() ; public int readX() { s.p() ; int x0 = x ; s.v() ; return x0 ; } public void writeX(int x0) { s.p() ; x = x0 ; s.v() ; } public int readY() { s.p() ; int y0 = y ; s.v() ; return y0 ; } public void writeY(int y0) { s.p() ; y = y0 ; s.v() ; } } </code></pre> <p>Here Semaphore is a class that uses <em>synchronized</em> methods to provide mutual exclusion.</p> <p>Now the following actions happen: </p> <ul> <li>Thread 0 calls o.readX() and finds it to be 0.</li> <li>Thread 1 writes 1 to x and then 1 to y using o.writeX(1) ; o.writeY(1) ;</li> <li>Thread 0 calls o.readY() getting 1 and then calls o.readX() .</li> </ul> <p>Could thread 0 read from its cache and find that x is 0? Why?</p> <hr> <p>EDIT</p> <p>Here is the Semaphore class</p> <pre><code>class Semaphore { private boolean available = true ; public synchronized void v() { available = true ; notifyAll() ; } public synchronized void p() { while( !available ) try{ wait() ; } catch(InterruptedException e){} available = false ; } } </code></pre>