File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Threadsafe? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Threadsafe?" Watch "Threadsafe?" New topic


O. Subramaniam

Joined: Aug 04, 2003
Posts: 17
how to make a servlet Threadsafe?
ib idris

Joined: Aug 02, 2003
Posts: 29
Use synchronized blocks or SingleThreadModel
Brian R. Wainwright
Ranch Hand

Joined: Aug 12, 2003
Posts: 92
I wouldn't recommend the SingleThreadedModel as it can have significant performance implications and your application may not be portable (since, I believe, the SingleThreaded implementation is specific to the servlet container). You must also still used synchronized blocks to resolve possible concurrency issues when accessing info in the application (ServletContext) and session scopes as well as when accessing you data source (unless your db classes are thread safe). That said you may as well do it yourself. Some tips:
1. synchronize blocks of code rather than whole methods and don't synchronize doPost, or doGet, but rather parts of it if necessary.
2. remember that since there is only one HttpServletRequest per thread, the only scope that is truly thread-safe is the request scope (not even your session is really really safe). Be aware of concurrency issues when accessing/mutating variables in other scopes. With this in mind, when possible, utilize request and method local attributes.
3. be as granular as possible when obtaining locks. For example, if you have a method that loads data from a file, synchronize on the FileStream object rather than the whole method. This will speed performance.
4. be conservative. synchronize only that which needs to be synchronized (you probably already gathered that).
Here's a better discussion than I can give:
Best of luck,
Chris Mathews
Ranch Hand

Joined: Jul 18, 2001
Posts: 2712
Listen to Brian, he is right on target for this!
Just to add one more deterrent against SingleThreadModel... it is deprecated in the upcoming Servlet 2.4 Specification. Take the time to truely make everything thread safe instead of applying the SingleThreadModel bandaid. Your code will thank you.
O. Subramaniam

Joined: Aug 04, 2003
Posts: 17
hi guys,
thank you very much for giving such a wonderful explanation

Subramaniam O
I agree. Here's the link:
subject: Threadsafe?
It's not a secret anymore!