Issue
When we create servlet, why class variables(instance and static variables) are NOT thread-safe?
Why methods doPost()
and doGet()
are thread-safe?
I think that each new request to servlet container creates new instance of servlet class (which extends HttpServlet
). This each instances have they own class variables that are hosted in memory, then why we must make these variables thread safe?
Solution
The servlet is instanciated only once: at loading. Then when clients make a requests, it's threaded.
This explains why you have to put monitors where it is necessary, etc.
Since doGet and doPost depend on a request, it is thread-safe : if you plan to do atomic operation in doGet and doPost, you should consider creating synchronized method/block.
Answered By - delannoyk
Answer Checked By - Gilberto Lyons (JavaFixing Admin)