title: Inter-process file locking in Java
body: <p>I haven't found anything specific, only threads like
  <a href="https://stackoverflow.com/questions/23055487/java-inter-process-mutex">that</a>, which doesn't show the implementation.</p>
  
  <p>I need to create a file lock shared between two or more processes(not threads!). I need to read/write in a file in one process and guarantee that no other process writes to the file in the same time. FileChannel.lock() doesn't do the job, because it throws an exception(OverlappingFileLockException) whenever the lock exists.</p>
  
  <p>I have two ideas how to achieve a inter-process mutex, but both seems a little bit bad to me.</p>
  
  <ol>
  <li><p>Repeat locking action until it works - quite disgusting, but simple and it should work I guess?</p>
  
  <pre><code>RandomAccessFile rFile = new RandomAccessFile(file, "rw");
  FileChannel channel = rFile.getChannel();
  FileLock lock;
  boolean locked = false;
  while(!locked) {
      try {
          lock = channel.lock();
          locked = true;
      } catch(OverlappingFileLockException e) {
          Thread.sleep(10);
      }
  }
  lock.release();
  </code></pre></li>
  <li><p>Whenever the exception is thrown, transform the current process into a server. Use ServerSocket to listen to other processes and Socket to communicate that lock.release() has been called. This one sounds like using a cannon to kill a fly to me.</p></li>
  </ol>
  
  <p>Is any of these 2 correct way of handling my problem? Or is there an already existing Java mechanism that allows locking a file across processes?</p>