• Post Reply Bookmark Topic Watch Topic
  • New Topic

Multiple requests hitting on the same servlet

 
Ko Ko Naing
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just would like to know if many people are hitting the same servlet on the same servlet container, will the container create as much servlet objects as the number of requests to respond to the people? Or will it create just as much threads as the number of requests to respond?

The main question is "Will mutliple servlet objects of the same servlet class be created in the container to respond to different requests?".

Thanks.
 
Bosun Bello
Ranch Hand
Posts: 1511
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Onky one instance of the servlet will be created, but multiple threads will be spun depending on the number of requests. That's assuming you do not implement (and you should not be) the SingleThreadModel interface.
 
Ko Ko Naing
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bosun.

I think my servlet is not implementing SingleThreadModel interface. So multiple threads will be spun to respond to the incoming requests. If I use synchronized(this) block to prevent global variable from being accessed by multiple threads, will that be enough?

I think that "this" in the brackets is of the current servlet object. If you say that only one instance of the servlet will be created, then the global variable accessed inside that synchronized(this) block will be safe, allowing only one thread to access the global variable at a time.

But if more than one instances of the servlet will be created, then I am sure that synchronized(this) block will not be safe to protect the global variable from being accessed by other instances(not just "this").

Thanks again, Bosun. Your reply really helped me...
 
Vishnu Prakash
Ranch Hand
Posts: 1026
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If I use synchronized(this) block to prevent global variable from being accessed by multiple threads, will that be enough?


Yes that will be sufficient to protect instance variables from being accessed by multiple threads provided you don't implement SingleThreadModel. But having instances variables in servlet is NOT considered best practice, because they are inherently NOT thread-safe and explicitly making it thread safe using synchronized(this) will affect concurrency.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!