MyTitle MyTitle - 1 month ago 8
Java Question

Thread-safe servlets

Why when we create servlet, only class variables(instance and static variables) are NOT thread-safe? Why methods doPost() and doGet() are thread-safed?
Btw why this class variables are NOT 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 housed in memory, then why we must make this variables thread safety?

Answer

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.