Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Servlet Instance variables are not thread safe?

 
warren li
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am confused with this part.

On page 202, the first dumb Q&A explained it.
but this is what I am thinking:

Multiple clients make multiple requests. Each request is allocated the same servlet but a different thread. Each thread basically is a different servlet "object" from the same servlet class. Since they are different servlet objects, the multiple requests modify the instance variables of the allocated object to itself. They don't access the servlet object allocated to other requests. Then how can the instance variables are non-thread safe?
Anyone can clarify it?

Thank you.
 
Tanveer Ahmad
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi warren,
I guess you have to restart reading the HF all over again. If you remember, the container creates only one instance of a servlet (well... generally). So you have only one servlet being accessed by more than one thread. This means instance vaiables are exposed to every thread.

Thanks
Tanveer
 
Saurabh Kumar
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Warren,

Container creates one instance of the servlet( either on startup or on first request).So, there is only one instance of the servlet no matter how many requests are received by the container.When container receives a request for a servlet, it creates a thread for the request. This thread then runs service method of the servlet. So there would be many threads running in the service method of single servlet instance.
So, since there is only one instance, the instance variables are still accessible to many threads, thus making them thread-unsafe. That's how instance variables are normally not thread safe.

There is one condition when instance variables can be thread safe- if your servlet implements "SingleThreadModel" interface. With this, the container creates an instance per request-thread.

Hope this helps.

Thanks and regards,
Saurabh
 
warren li
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. I understand now.
After reading the whole Q&A session, I got it. Only 1 servlet object, but many threads.
 
Niranjan Deshpande
Ranch Hand
Posts: 1277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
understanding the thread safety needs very strong knowledge of java threads
...the SCJP stuff
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic