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.
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:
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?
You've enumerated the possible solutions except the obvious one: remove the dependency on that file
Is there another way for the threads to obtain that data instead of reading it from a file? How about setting up some kind of process who is responsible for coordinating access to that information instead of having all the threads read the file.
A. Sounds like it's time for a database :-). Rather than having a shared file what about storing the data in a database.
B. Alternatively - layering:
Nest 2 inside 1.
Still has the clean-up problem.
C. Alternatively some kind of write to new file/rename strategy so that reader don't need to lock maybe?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With