title: How to lock a file on different application levels?
body: <p>Here's the scenario: I have a multi threaded java web application which is running inside a servlet container.
  The application is deployed multiple times inside the servlet container. There are multiple servlet containers
  running on different servers.</p>
  
  <p>Perhaps this graph makes it clear:</p>
  
  <pre><code>server1
  +- servlet container
     +- application1
     |  +- thread1
     |  +- thread2
     +- application2
        +- thread1
        +- thread2
  server2
  +- servlet container
     +- application1
     |  +- thread1
     |  +- thread2
     +- application2
        +- thread1
        +- thread2
  </code></pre>
  
  <p>There is a file inside a network shared directory which all those threads can access. And they do access the file frequently.
  Most of the time the file is only read by those threads. But sometimes it is written.</p>
  
  <h3>I need a fail safe solution to synchronize all those threads so data consistency is guaranteed.</h3>
  
  <hr>
  
  <p><strong>Solutions which do not work (properly)</strong>:</p>
  
  <ol>
  <li><p><em>Using java.nio.channels.FileLock</em><br>
  I am able to synchronize threads from different servers using the FileLock class. But this does not work for threads
  inside the same process (servlet container) since file locks are available process wide.</p></li>
  <li><p><em>Using a separate file for synchronization</em><br>
  I could create a separate file which indicates that a process is reading from or wrinting to the file. This solution
  works for all threads but has several drawbacks:</p>
  
  <ul>
  <li>Performance. Creating, deleting and checking files are rather slow operations. The low weight implementations with one synchronization file will prevent parallel reading of the file.</li>
  <li>The synchronization file will remain after a JVM crash making a manual clean up necessary.</li>
  <li>We have had already strange problems deleting files on network file systems.</li>
  </ul></li>
  <li><p><em>Using messaging</em><br>
  We could implement a messaging system which the threads would use to coordinate the file access. But this seems too complex for this problem. And again: performance will be poor.</p></li>
  </ol>
  
  <p>Any thoughts?</p>