Why Servlets are not thread Safe? [duplicate]

I need to know why the servlets are not thread safe ? And whats the reason that in Struts 2.0 framework controller servlet is thread safe ?


Solution 1:

I need to know why the servlets are not thread safe ?

Servlet instances are inherently not thread safe because of the multi threaded nature of the Java programming language in general. The Java Virtual Machine supports executing the same code by multiple threads. This is a great performance benefit on machines which have multiple processors. This also allows the same code to be executed by multiple concurrent users without blocking each other.

Imagine a server with 4 processors wherein a normal servlet can handle 1000 requests per second. If that servlet were threadsafe, then the web application would act like as if it runs on a server with 1 processor wherein the servlet can handle only 250 requests per second (okay, it's not exactly like that, but you got the idea).

If you encounter threadsafety issues when using servlets, then it is your fault, not Java's nor Servlet's fault. You'd need to fix the servlet code as such that request or session scoped data is never assigned as an instance variable of the servlet. For an in-depth explanation, see also How do servlets work? Instantiation, sessions, shared variables and multithreading.

And whats the reason that in Struts 2.0 framework controller servlet is thread safe ?

It is not thread safe. You're confusing the Struts dispatcher servlet filter with Struts actions. The struts actions are re-created on every single request. So every single request has its own instance of the request scoped Struts action. The Struts dispatcher servlet filter does not store them as its own instance variable. Instead, it stores it as an attribute of the HttpServletRequest.

Solution 2:

Servlets are normal java classes and thus are NOT Thread Safe.

But that said, Java classes are Thread safe if you do not have instance variables. Only instance variables need to synchronize. (Instance variable are variables declared in the class and not in within its methods.

Variables declared in the methods are thread safe as each thread creates it own Program Stack and function variables are allocated in the stack. This means that variable in a methods are created for each thread, hence does not have any thread sync issues associated.

Method variables are thread-safe, class variables are not.

Solution 3:

There is a single instance of a servlet per servlet mapping; all instance properties are shared between all requests. Access to those properties must take that in to account.

Struts 2 actions (not "controller servlet", they're neither servlets nor controllers) are instantiated per-request. Action properties will be accessed only by a single request's thread.