爲何servlets是非線程安全的?

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.
Servlet實例天生就是非線程安全的,由於Java的多線程特性。JVM支持在多線程中運行同一段代碼。這是一個很好的性能優點在擁有多個處理器的機器上。這也容許相同的代碼在併發執行下不會阻塞。web

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).
想象一個有4個處理器的服務器在一個正常的servlet能夠處理每秒1000個請求。若是servlet是線程安全的,則web應用就像運行在一秒只能處理250個請求的單處理器機器上(是的,雖然不是徹底同樣,可是你應該理解了)。安全

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, session variables and multithreading.
若是你在使用servlets的時候你遇到了線程問題,那是你的錯誤,而不是Java的錯誤更不是Servlets的錯誤。你須要修改Servlet中的如:不要將request範圍或session範圍的實例變量定義在Servlet對象上。深刻解釋下請參考 How do servlets work? Instantiation, sessions, shared variables and multithreading服務器

參考: Why Servlets are not thread Safe? [duplicate]session

相關文章
相關標籤/搜索