When we create servlet, why class variables(instance and static variables) are NOT thread-safe?
Servlets typically run on multithreaded servers. So a servlet must handle concurrent requests and should be careful to synchronize access to shared resources. Shared resources include in-memory data such as instance or class variables and external objects such as files, database connections, and network connections. Since multiple threads may mutate the state of shared data, shared data is not thread safe.
Why methods doPost() and doGet() are thread-safe?
doPost() and doGet() are thread safe if you are using local variables in those methods. If you mutate the state of shared variables (instance or static variables) in these methods, doPost() and doGet() are not thread safe.
This each instances have they own class variables that are hosted in memory, then why we must make these variables thread safe?
One instance exists for one Servlet. Requests like doGet()
or doPost()
create multiple threads on same instance. As long as you use local varaibles in these methods, code is thread safe.
You can find good info in this post:
How do servlets work? Instantiation, sessions, shared variables and multithreading