title: java forcing acquire of lock?
body: <p>I am working with a somewhat outdated workflow engine, it allows for defining an individual step that executes Java code, but not more than this.</p>
  
  <p>Each invocation of a workflow process operates in its own thread, with any subprocesses executing in the same thread synchronously.</p>
  
  <p>The workflow engine does not allow for capturing of all exceptions that occur in a process.  I need to make some subprocesses operate single-threaded, i.e. to wait if another thread is executing the subprocess.</p>
  
  <p>All I could come up with so far is to acquire a lock at the first step in a subprocess, and release it at the end steps.  If an exception occurs in the process, it isn't always possible to capture it.</p>
  
  <pre><code>... s_lock = new ReentrantLock(); ...
  ... s_timeout = 10; ...
  
  public static void acquireLock() throws InterruptedException {
      if( !s_lock.tryLock(s_timeout, TimeUnit.SECONDS)) {
          System.out.println("WARN: Forcing acquire of lock.");
          s_lock = new ReentrantLock();   // discard old lock and create a new one
          s_lock.lock();
      }
  }
  
  public static void releaseLock() {
      if( s_lock.isHeldByCurrentThread()) {
          s_lock.unlock();
      } else {
          System.out.println("WARN:  lock not held by thread.");          
      }
  }
  </code></pre>
  
  <p>There must be a better way?  Is it possible to automatically release the lock if a thread terminates?</p>