title: Multiple lock single unlock in Java?
body: <p>I am implementing my version of <code>RunnableFuture</code> and faced the need to atomize state change at the end of <code>run()</code> method. The specific list of state fields does not matter. The point it that <code>Runnable</code> may finish either by exception, or normally. Hence it can either visit tail of <code>try</code> block, or not. Also I can visit <code>catch</code> block, then <code>finally</code> block. </p>
  
  <p>All these 3 places should be changed atomically, but I can't see "interblock" locking construction. So, I used <code>getHoldCount()</code> to decide whether to call <code>lock()</code>:</p>
  
  <pre><code>public void run() {
  
        Runnable runnable;
  
        lock.lock();
        try{
           runnable = this.runnable;
           done = false;
           running = true;
           result = null;
        }
        finally {
           lock.unlock();
        }
  
        try {
           if( !cancel ) {
              runnable.run();
           }
  
           if( lock.getHoldCount()==0 ) lock.lock();
           exception = null;
           result = finalResult;
  
        }
        catch (Exception e) {
  
           if( lock.getHoldCount()==0 ) lock.lock();
  
           exception = e;
           result = null;
  
        }
        finally {
           if( lock.getHoldCount()==0 ) lock.lock();
           done = true;
           running = false;
  
           lock.unlock();
        }
  
     }
  </code></pre>
  
  <p>Is this correct and is there any better way to do this?</p>