2

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?

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
WelcomeTo
  • 19,843
  • 53
  • 170
  • 286

2 Answers2

9

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.

delannoyk
  • 1,216
  • 1
  • 12
  • 22
  • thanks. i.e. if I have class with not thread-safe class variable, I should to use this variable inside doGet(doPost) method in synchronized block or I should transfer code that use this variable into synchronized method and use this method in doGet(doPost)? – WelcomeTo Jan 14 '12 at 09:47
  • If i had to do that, i'll use a setter which would be a synchronized method. – delannoyk Jan 14 '12 at 10:51
0

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

Community
  • 1
  • 1
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211