Jamel Tayeb wrote:
>
> Hi Everybody,
> I want to read a configuration file from my Jsp application but I am
> having problems that I suspect are due to concurrent access to this
> file by multiple instances of the application.
>
> Does anybody know how to avoid conflicts? Will putting the code
> in a method that is declared synchronised solve the problem and
> guarantee safety? When two instances of a synchronised method
> (belonging to the same class) are executing, does the servlet engine
> detect and coordinate their execution?

Concurrent access to the web resource is natural in JSP/Servlet
environment. You can't rely on a servlet class that all information
stores in its instance variables, if you do, you're asking for a
trouble. To avoid conflicts you have to queue all the requests and run
them one by one or just put the "sensitive" code inside synchronized
block.

In your particular situation, you caould create a helper class, e.g.
SaveFile. One of the methods could be save() and to create an instance
of the class, you'll have to call getInstance(). It decreses time to
prepare file and do any file-related tasks. So, your code would look
like:

public class SaveFile {
  private static SaveFile instance = null;
  public static SaveFile getInstance() {
    if (instance == null)
      instance = new SaveFile();
    return instance;
  }

  private RandomAccessFile raf = null;

  private SaveFile() {
    // open file
    // do something...
  }

  public void save() {
    synchronized(raf) {
      doSomethingWithRaf();
    }
  }
}

You may also define save function as synchronized in the above snippet
since you synchronizes all function's code, so actually whole function.

Now, inside your JSP code (actually it should be invisible for HTML
developer, so I'd suggest that that code should move to servlet or some
other Tag), you'll write

<%
  SaveFile saveFile = SaveFile.getInstance();
  saveFile.save();
%>

Actually, you could also put SaveFile object inside session, so the
following servlets/jsps would use it without a need to call
getInstance() method.

Hope, you've got an idea.

> Jamel Tayeb

Jacek Laskowski

===========================================================================
To unsubscribe: mailto [EMAIL PROTECTED] with body: "signoff JSP-INTEREST".
Some relevant FAQs on JSP/Servlets can be found at:

 http://java.sun.com/products/jsp/faq.html
 http://www.esperanto.org.nz/jsp/jspfaq.html
 http://www.jguru.com/jguru/faq/faqpage.jsp?name=JSP
 http://www.jguru.com/jguru/faq/faqpage.jsp?name=Servlets

Reply via email to