• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Servlets instances and threads

 
Leandro Melo
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all.
I'm trying to clearify something. I've searched the forum and it already help me a little. Thus, I'd just like to make one statement so others can tell me if I'm right or wrong.

Initially, when I read (Head First Servlets) that there were always only one instance of each servlet and diferent requests were treated by different threads (except in SingleThreadModel), I thought that maybe the servlet interface extended interface Runnable (and the service() method was being called inside run()). I checked it out and verified I was wrong. So, now I'd like to cerify if this is what really happens.

The container loads only one instance of each servlet. It calls it's init() method after the instance is created. For any requests that hit the server and should be handled by this this servlet, it spwans a thread that will call the serlvet's service() method. So, this methods are being called on the same instance of the servlet (if 100 requests hit the server for that servlet, 100 threads will be spwanned and they will call the service() method on the same instance of a servlet). This is why servlets are not thread safe. Am I correct?

Thanks.
 
Vishwa Kumba
Ranch Hand
Posts: 1066
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Leandro Melo:
The container loads only one instance of each servlet. It calls it's init() method after the instance is created. For any requests that hit the server and should be handled by this this servlet, it spwans a thread that will call the serlvet's service() method. So, this methods are being called on the same instance of the servlet (if 100 requests hit the server for that servlet, 100 threads will be spwanned and they will call the service() method on the same instance of a servlet). This is why servlets are not thread safe. Am I correct?


Yes, my view is also the same. Servlets are not thread-safe if you use instance/class member variables that are not read-only. As long as you don't use them, it is fine. (i.e-servlets are thread-safe in most applications).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic