title: Java: Obtaining multiple locks
body: <p>How do I obtain multiple locks in cases like this:</p>
  
  <pre><code>public class DoubleCounter
  {
      private int valA = 0;
      private int valB = 0;
  
      private Object lockA = new Object();
      private Object lockB = new Object();
  
      public void incrementA()
      {
          synchronized (lockA)
          {
              valA++;
          }
      }
  
      public void incrementB()
      {
          synchronized (lockB)
          {
              valB++;
          }
      }
  
      public void print()
      {
          //I have to obtain both lockA &amp; lockB before executing this:
          System.out.format("valA: %d\nvalB: %d", valA, valB);
      }
  }
  </code></pre>
  
  <p>Keep in mind I don't want the execution of <code>incrementA()</code> by one thread to block the execution of <code>incrementB()</code> by another - therefore I don't want to use synchronized methods.</p>
  
  <p>Similar (not exactly the same) question has been asked twice on StackOverflow but I still haven't got the answer I was looking for. The only thing I know is that I shouldn't nest one <code>synchronized()</code> inside another <code>synchornized()</code>.</p>