Does using the synchronized and static blocks in servlets is an good practice in coding. Whether it will affect the performance of the system
Asked
Active
Viewed 1,850 times
2 Answers
2
Servlets are processing elements and are expected to be inherently thread-safe as the servlet container would generally create one instance of the servlet and call the appropriate http methods on this single instance for each incoming request, in separate threads.
So, static blocks are generally limited to initializing something specific to the Servlet class as such. Synchronized blocks are better avoided as they will become a bottleneck when many requests come into the system simultaneously. You should expand your question with your use case for specific comments, though.

Vikdor
- 23,934
- 10
- 61
- 84
-
This is heavily explained and detailed by BalusC in the link posted on my comment. I just can't post a link as an answer, and let me tell you, BalusC is an expert in Web Application Design. – Luiggi Mendoza Oct 23 '12 at 07:07
0
Synchronized block will make your servlet response slow so it always better to avoid synchronized block unless you required thread safe.

Subhrajyoti Majumder
- 40,646
- 13
- 77
- 103
-
That is a very general and not necessarily correct statement. It might also make the application threadsafe, which would be desirable... In any case, it is impossible to answer without more knowledge on the concrete usage. – Anders R. Bystrup Oct 23 '12 at 07:02
-
@AndersRostgaardBystrup not really, a Web server creates only 1 instance of every Servlet and reuse them in many threads. Making a request waiting for another request it's a bad design. And if you want to make your application threadsafe, read the link in my comment to OP question. – Luiggi Mendoza Oct 23 '12 at 07:06
-
@Luiggi, I am aware of that, thank you ;-) My point was merely that the original answer by Quoi was very terse. And actually most webservers create a pool (not just one) of servlet object and reuse them. – Anders R. Bystrup Oct 23 '12 at 07:09