title: Atomic operation on read/write variable in java
body: <p>I have a java class as below:</p>
  
  <pre><code>public class Example implements Runnable {
  
      private int num;
  
      ...
  
      // Getter
      public int getNum(){
          return this.num;
      }
  
      // Setter    
      public void addToNum(int amount) {
  
          if (this.amount&gt; 0) {
              this.num += amount;
          }
      }
  
      ...
  }
  </code></pre>
  
  <p>This class can be instantiated by multiple threads. Each of this instances have its own 'num', that is, I do not want 'num' variable to be shared between all them.</p>
  
  <p>To each instance, multiple threads can be accessed in concurreny in order to read/write 'num' variable. So what is the best option to protect read/write operations on 'num' variable in order to they are atomic operations?</p>
  
  <p>I know that in case on C# it can be done using lock(object) like below link but in java I have no idea (I am new on it):</p>
  
  <p><a href="http://blog.coverity.com/2014/03/12/can-skip-lock-reading-integer/" rel="nofollow">Atomic operations on C#</a></p>