title: Java synchronized blocks -- lock objects
body: <p>In the sample code </p>
  
  <pre><code>public class MsLunch {
  private long c1 = 0;
  private long c2 = 0;
  private Object lock1 = new Object();
  private Object lock2 = new Object();
  
  public void inc1() {
      synchronized(lock1) {
          c1++;
      }
  }
  
  public void inc2() {
      synchronized(lock2) {
          c2++;
      }
  }
  }
  </code></pre>
  
  <p>on <a href="http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html" rel="nofollow noreferrer">this</a> page, </p>
  
  <p><strong>lock1</strong> and <strong>lock2</strong> are controlling the updates on <strong>c1</strong> and <strong>c2</strong> resply. </p>
  
  <p>However, </p>
  
  <pre><code>    synchronized(lock2) 
  </code></pre>
  
  <p>is acquiring the lock of the object <strong>lock1</strong> and releasing it when the synchronized block </p>
  
  <pre><code>    synchronized(lock1) {
          c1++;
      }
  </code></pre>
  
  <p>is executed. </p>
  
  <p>While this block is being executed, there may be 
  an update on member <strong>c1</strong> of <strong>this</strong> object still-- and I don't 
  see how this update is being prevented by 
  synchronizing on <strong>lock1</strong> as in the code. </p>
  
  <p>It is the object <strong>lock1</strong> that there is exclusive access on-- 
  and nothing else(?)</p>
  
  <p>So, how is the implementation  </p>
  
  <pre><code>public void inc1() {
      synchronized(lock1) {
          c1++;
      }
  }
  </code></pre>
  
  <p>in the above code different from </p>
  
  <pre><code>public void synchronized inc1() {
          c1++;
  }
  </code></pre>
  
  <p>or even </p>
  
  <pre><code>public void inc1() {
      synchronized(c1) {
          //do something on c1
      }
  }
  </code></pre>
  
  <p>when <strong>c1</strong> is an object but not a primitive?  </p>
  
  <p>What am I missing here ?</p>
  
  <p>Note: I saw </p>
  
  <p><a href="https://stackoverflow.com/questions/3369287/synchronized-block-lock-object-question">What is the difference between synchronized on lockObject and using this as the lock?</a></p>
  
  <p>and </p>
  
  <p><a href="https://stackoverflow.com/questions/3047564/java-synchronized-method-lock-on-object-or-method">Java synchronized method lock on object, or method?</a></p>
  
  <p>among some other discussions. </p>