dimanche 23 décembre 2018

Paradigm : Pure functions are thread-safe

Servlet : Why-servlets-are-not-thread-safe


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.