Issues with Integrity of Instance Variables in jsp/servlets

When isThreadSafe is true, then the page does not implement SingleThreadModel, but rather implements the MultiThreadedModel. The default handling for this servlet, as defined by the servlet spec is to create ONE instance of the servlet, which handles all requests. Thus there can be multiple threads going through a JSP/servlet service method. By default a page is threadsafe, that is it does not implement SingleThreadModel but rather the MUltiThreadedModel. So with MultiThreadedModel, session and request are still separate as they are not instance variables and they are just input to the method of the servlet, they don’t belong to the servlet instance. They are sent in when service(httprequest etc…) method is invoked, so they are like local variables. This is not true for instance variables defined in the servlet. Different threads are manipulating a single instance variable.
One way to retain data integrity of local variables is to use the SingleThreadModel(isThreadSafe=”false”).
Normally servlets (or jsps) are kept as a single instance. The service() method is run on separate threads. Now when we explicitly say isThreadSafe =”false” (SingleThreadModel in servlets) the service() method becomes single-threaded, that is the servlet instance is accessed by only one thread at a time. Normally only one instance is still available and this can be a bottleneck for performance. However if you make it single threaded, some servlet engine implementations keep a pool of instances to avoid performance bottlenecks. In such cases, this causes data integrity problems. So the suggestion is don’t make it single threaded – let the isThreadSafe=true which is default.
Then you are assured of having a single instance and multiple threads, but make the instance variables synchronized to manage the conflict between threads. why synchronize? You are trying to keep the integrity of the values stored as instance variables in the servlet. The instance variable is shared by multiple threads. Different threads are manipulating a single instance variable and so you need to synchronize the instance to keep the integrity of instance variable.
This only applies for instance variables outside the service method. Local variables are stored on the stack – each thread has its own stack, they are never shared.

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Comments are closed.

%d bloggers like this: