Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threadsafe?

 
O. Subramaniam
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how to make a servlet Threadsafe?
 
ib idris
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use synchronized blocks or SingleThreadModel
http://galileo.spaceports.com/~ibidris/
 
Brian R. Wainwright
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
http://www.theserverside.com/discussion/thread.jsp?thread_id=291
Best of luck,
Brian
 
Chris Mathews
Ranch Hand
Posts: 2712
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys,
thank you very much for giving such a wonderful explanation

regards
Subramaniam O
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic