java - How to lock a file on different application levels? -


Here's the scenario: I have a multi-threaded Java web application that is running inside the servlet container. Servicelet containers have been deployed several times inside the container.

Perhaps this graph makes it clear:

  server1 + - servlet container + - application1 | + - thread 1 | + - Thread 2 + - Application 2 + - Thread 1 + - Thread 2 Servers 2 + - Servlet Container + - Application 1 | + - thread 1 | + - Thread 2 + - Application 2 + - Thread 1 + - Thread 2  

There is a file inside a network shared directory that can access all threads. And they often access the file. Most of the time the file is read only by those threads. But sometimes it is written.

I need a fail-safe solution to synchronize all those threads, so data stability is guaranteed.


Those who do not resolve (properly) :

  1. java.nio.channels.FileLock Use
    I'm able to synchronize threads from different servers using the FileLock class.

  2. Use a different file for synchronization but it does not work for the thread inside the same process (servlet container)


  3. I can create a separate file which indicates that someone is reading a process or writes a file. This solution works for all threads, but there are many drawbacks:

    • Creating, deleting and checking display files is rather slow operation. Low load implementation with a synchronization file will prevent parallel reading of the file.
    • After a JMM accident, the synchronization file will be created, so the manual can be cleared.
    • We already have strange problems in removing files on the network file system.
  4. Using the message
    We can implement a messaging system that will use the thread to sync the file usage But it seems very complicated for this problem and then: the performance will be bad.

Any thoughts?

If you want to write a file hardly, about writing a file under a temporary name And then what's the way to change names to make "view" for readers?

This only works reliably the Unix file system, though. On windows, you will have to handle this issue in some process (to read) to open the file. In this situation, rename will fail. Just try again until the name change is successful.

I suggest testing it well because you can get in the crowd: There are many read requests that the author can not change the working file for a long time.

If this is the case, then readers should check the temporary file and wait for a few moments until the file disappears.


Comments