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.
Perhaps this graph makes it clear:
server1
+- servlet container
+- application1
| +- thread1
| +- thread2
+- application2
+- thread1
+- thread2
server2
+- servlet container
+- application1
| +- thread1
| +- thread2
+- application2
+- thread1
+- thread2
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.
I need a fail safe solution to synchronize all those threads so data consistency is guaranteed.
Solutions which do not work (properly):
Using java.nio.channels.FileLock
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.Using a separate file for synchronization
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:- 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.
- The synchronization file will remain after a JVM crash making a manual clean up necessary.
- We have had already strange problems deleting files on network file systems.
Using messaging
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.
Any thoughts?