Friday, May 02, 2008

Web Applications & Threadsafe Servlets

When writing web applications in Java one thing which almost every Java programmer would have to do at some point or the other is to write servlets. What does one mean when they say you should write servlets that are "Threadsafe" ?

To answer this question, first one should understand what multithreading and the servlet life cycle model are. A servlet container manages the life cycle of a servlet, meaning the servlet's creation, execution and destruction. Among several things a servlet container helps you in building efficient web applications by managing the life cycle of a servlet. In general the way it does this is to maintain a single instance of the servlet in the memory. Each HTTP request that the servlet container receives results in a thread being spawned to this "One Single" instance of servlet. For examples 10 simultaneous HTTP requests will result in 10 thread of execution on the same instance of servlet in the memory.

One very important thing which often programmers miss out here is that one should almost never user instance variables in a servlet unless they are absolutely needed and you know exactly what you are going to do with them. The reason is that as mentioned above there is only one instance of servlet in the memory. Therefore all the threads (HTTP requests) will be sharing the same piece of memory allocated for the instance variables which are bound to the servlet class. As a result any write operations being done on these variables are being done on the same memory allocation. This may result in unexpected and often bizarre behavior in web applications.