title: Increments and decrements in multi threaded environment
body: <p>I am trying the classic increment/decrement of an int variable in a multi threaded environment. This is my sample code. </p>
  
  <pre><code>public class SyncIncDec {
  
  
      public static void main(String[] args) {
  
          SyncCounter count = new SyncCounter();
  
          Thread incThread = new Thread(() -&gt; {
              count.increment();
          });
  
          Thread decThread = new Thread(() -&gt; {
              count.decrement();
          });
  
          Thread displayThread = new Thread(() -&gt; {
              System.out.println("Count value : " + count.getX());
          });
  
          incThread.start();
          decThread.start();
          displayThread.start();      
  
          try {
              incThread.join();
          } catch (InterruptedException e) {
  //          e.printStackTrace();
          }
  
          try {
              decThread.join();
          } catch (InterruptedException e) {
  //          e.printStackTrace();
          }
  
          try {
              displayThread.join();
          } catch (InterruptedException e) {
  //          e.printStackTrace();
          }
  
      }
  
  }
  
  
  class SyncCounter {
  
      private int x=0;
  
      public SyncCounter() {
          super();
      }
  
      public SyncCounter(int y) {
          super();
          x = y ;
      }
  
      synchronized int  getX() {
          return x; 
      }
  
      void setX(int y) {
          x = y ;
      }
  
      void increment() {
          ++x;
      }
  
  
      void decrement() {
          --x;
      }
  
  }
  </code></pre>
  
  <p>Though I have used join() method for all the three threads, I still get inconsistent results. 
  Doesn't join here mean for the main thread to wait until each of the thread has completed its execution? I even tried adding synchronized to each of three method signatures; yet I get inconsistent results. </p>
  
  <p>Apart from using Atomic version of the variable, how else can I ensure that I get 0 always?</p>