1

I'm writing a Web Application based on Tomcat and Java Servlets. In my case, there are some (different) Servlet that have to access to the same file, and I need a mechanism to synchronized these accesses.

I tried with a new Servlet (with empty doGet() and doPost() methods) that I called 'Controller', in order to use it as a 'container' for each object I need (locks, condition variables, ...). Unfortunately, this approach is based on using the method getServlet(name), from ServletContext, that is deprecated and it doesn't work in my case.

Is there any known solution to this kind of problems?

Mike Tunnicliffe
  • 10,674
  • 3
  • 31
  • 46
Vito Gentile
  • 13,336
  • 9
  • 61
  • 96

2 Answers2

3

These kind of problems are usually solved by introducing an extra layer of abstraction.
Encapsulate the access to the file inside an object and use this new object to coordinate the access to the file.
The servlets will all use this intermediate object to access the file and this object will take care of any concurrency/multithreading issues. No need for new servlet that you say.
You can use the Servlet Context to store the object

Cratylus
  • 52,998
  • 69
  • 209
  • 339
  • Thank you very much for the answer. Is the ServletContext object I can obtain using getServletContext() the same for each Servlet of my Web Application? – Vito Gentile Aug 30 '12 at 17:51
  • @VitoShadow:Yes the same.There is one context per "web application" per Java Virtual Machine. – Cratylus Aug 30 '12 at 17:54
  • So in this case, you'd introduce a class that would contain synchronized methods for reading and writing to the XML file. Is that correct? – W.K.S May 26 '13 at 16:31
0

You can use file locking using FileChannel.lock:

How can I lock a file using java (if possible)

Community
  • 1
  • 1
Brian
  • 17,079
  • 6
  • 43
  • 66