Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Threading in servlet  RSS feed

 
trupti nigam
Ranch Hand
Posts: 640
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a basic question about threading in servlet.
If the servlet implements the singletread interface then the container generates multiple instances of the servlet making sure that one client request is served by a single instance and no two threads run the servlet's service method.

If you do not implement it then the service method is multithreaded by default. So you need to synchronise the access to the shared resources. but it also mentions not to synchronise the servlet code as it can be preformance bottleneck. Isn't it a contradicting statement.
Is my above understanding correct about the servlet threading?

Thanks,
Trupti
 
Vishnu Prakash
Ranch Hand
Posts: 1026
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If the servlet implements the singletread interface then the container generates multiple instances of the servlet making sure that one client request is served by a single instance and no two threads run the servlet's service method.

If you do not implement it then the service method is multithreaded by default.


Your understading is correct till this here.


So you need to synchronise the access to the shared resources.


There are six fundamental variable scopes in a webapp.

* Application (servlet context) scope attributes
* Session scope attributes
* Request scope attributes
* Local method variable (or JSP page scope attributes)
* Servlet instance variable
* Servlet class variable(static variables)

In general, only the local/method variables and Request scope attributes are thread-safe. Whenever, you access or modify a variable/attribute in any of the other scopes you should synchronize.

You can use synchronized blocks to synchronize only on those objects(Session, context) instead of synchronizing the entire service method.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!