title: What is the importance of synchronized method in stopping one Thread from another?
body: <p>From the book "Effective java" i have following famous code of stopping one thread from another </p>
  
  <pre><code> public class StopThread {
       private static boolean stopRequested;
       private static synchronized void requestStop() {
            stopRequested = true;
       }
       private static synchronized boolean stopRequested() {
            return stopRequested;
       }
       public static void main(String[] args)
                              throws InterruptedException {
            Thread backgroundThread = new Thread(new Runnable() {
                 public void run() {
                     int i = 0;
                     while (!stopRequested()) {
                         i++;
                     }
                 }
            });
            backgroundThread.start();
            TimeUnit.SECONDS.sleep(1);
            requestStop();
       }
  }
  </code></pre>
  
  <p>A line is written there that is "<strong>synchronization has no effect unless both read and write
  operations are synchronized.</strong>"But it is clear that if we don't use <code>synchronized</code> keyword with method <code>requestStop</code> the code will work fine,i.e,it terminates nearly after 1 second which is desired.One thing more here is that if we don't synchronize both the method we will(most probably) go into infinite loop because of code optimization.So my questions are:-<br>
  1.How and in what scenario things can go wrong if we don't synchronize 'stopRequested' method?Although here if we don't synchronize it,the program runs as desired,i.e,it terminates nearly in 1sec.<br>
  2.Does <code>synchronized</code> keyword enforces the VM to stop optimization each time? </p>