Monday, November 28, 2005

Are doGet and doPost methods in servlets thread safe? Should we Synchronize them to make thread safe.

The answer is "NO", the doGet and doPost (any doXyz) methods are not synchronized and thus not thread-safe. However, it is a very bad practice to synchronize these methods for your own servlet classes. The reason is that it reduces the servlet's ability to scale; IOW(In Other Words), to handle large numbers of concurrent requests.

Synchronize the smallest block of code that accesses or modifies a shared memory state. Remember: synchronizing reduces the scalability and at times the responsiveness of your webapp (any application, really) so try to limit or even remove the need for synchronization.

There are six fundamental variable scopes in a webapp. Which of these scopes are truly thread-safe?

  • Application (servlet context) scope attributes
  • Session scope attributes
  • Request scope attributes
  • Local method variable (or JSP page scope attributes)
  • Servlet instance variable
  • Servlet class variable

In general, only the local/method variables and Request scope attributes are thread-safe. Whenever, you access or modify a variable/attribute in any of the other scopes you should synchronize.


This topic (making a webapp thread-safe) is rather complex and one that cannot be resolved in a single answer. So, what I would recommend is that you study fundamental aspects of concurrent programming. I wouldrecommend Doug Lea's book Concurrent Programming in Java. It is a rich study of this broad topic. However, I will warn you that it is also very dense reading.... not exactly a Head-First experience. This is just the beginning of a very rich and interesting topic.

Click here to read more about thread safety


Post a Comment

<< Home