Instance Variable Declaration in a Servlet vs Instance Variables Declaration in Handler classes

There is a common misunderstanding of how servlet instance variables work.
Let’s consider a Servlet, say the Controller Servlet in Struts(Action Servlet). At any given time there is only one instance of this Servlet. This Servlet is multi-threaded so it does not have state. State in the sense it has no instance variables with values. Many requests can be serviced by this Servlet by running multiple threads on the same instance.
Instance variables can be declared in a servlet but these variables are shared by all threads. No single thread can rely on using the variable for itself, so threads can never depend on the value of an instance variable of a Servlet.
This Servlet passes control to handlers say Action classes in Struts. There are multiple instances of these action classes with their own state and these action classes are not multi-threaded in that sense.
There is one multi-threaded Servlet and multiple handler classes running on different threads. One multi-threaded Servlet can create new action-class instances which are dedicated instances.

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: