title: How to lock a java method to protect multiple invocations
body: <p>I have an application that every 15 minutes or so does a replication from a remote database.  It just keeps the two repositories in sync.  Once this replication is going it is not possible to do it again.  I have setup the following structure but I'm not sure if it is the correct approach.</p>
  
  <pre><code>public class ReplicatorRunner {
  
         private static Lock lock = new ReentrantLock();
  
         public replicate() {
  
             if (lock.tryLock()) {
                 try {
                     // long running process
                 } catch (Exception e) {                   
                 } finally {
                     lock.unlock();
                 }               
             } else {
                 throw new IllegalStateException("already replicating");
             }
  
         }
  
  }
  
  public class ReplicatorRunnerInvocator {
  
      public void someMethod() {
  
          try {
              ReplicatorRunner replicator = new ReplicatorRunner();
              replicator.replicate();
          } catch (IllegalStateException e) {
              e.printStackTrace();
          }
  
      }
  
  }
  </code></pre>
  
  <p>The <code>ReplicatorRunner</code> is the class owning the method <code>replicate</code> which can only be run one at a time.</p>
  
  <p>Edit.
  I need the next call to fail (<em>not block</em>) if the method is already running on any instance.  </p>