title: How to handle stale data in java concurrency?
body: <p>I am following the book '<strong>Java Concurrency In Practice</strong>' to understand Java Concurrency in detail. Then i came across a term called '<strong>Stale Data</strong>'.</p>
  <blockquote>
  <p>Book Says: Insufficiently Synchronized programs can cause surprising
  results--&gt;Stale data.</p>
  </blockquote>
  <p>There is an example given in the book, which protects the mutator methods using '<strong>synchronized</strong>' Keyword &amp; uses '<strong>@GuardedBy</strong>' annotation on its field. I thought of testing it.</p>
  <pre><code>import net.jcip.annotations.*;
  public class ThreadTest4 extends Thread{
      
      private MyWork4 myWork= new MyWork4();
      
      public static void main(String[] args){
          ThreadTest4 thread1 = new ThreadTest4();
          ThreadTest4 thread2 = new ThreadTest4();
          ThreadTest4 thread3 = new ThreadTest4();
          ThreadTest4 thread4 = new ThreadTest4();
          
          thread1.start();
          thread2.start();
          thread3.start();
          thread4.start();
          
      }
      
      public void run(){
              myWork.setA();
              System.out.println(myWork.getA());
      }
  }
  
  class MyWork4{
      
      @GuardedBy(&quot;this&quot;)  private static int a;
      
      public synchronized int getA(){
          return a;   
      }
      
      public synchronized void setA(){
          a++;
      }
      
  }
  </code></pre>
  <p>But it still surprises me with its results! What can be the reason?</p>
  <p><a href="https://i.stack.imgur.com/t8bmk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t8bmk.png" alt="enter image description here" /></a></p>