This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Servlet and syncrhonized block.

 
Val Dra
Ranch Hand
Posts: 439
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any request to the servlet will spawn a new thread a separate copy of a servlet will be running is that true ? If so what if i have a syncrhonized block in a servlets doGet() which does some lengthy operation , will it block any other request to this servlet until i leave the sync block ? or is it just for that servlets request for that user ? I need your help on this , thanks.
Val.
 
Bosun Bello
Ranch Hand
Posts: 1511
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, any other access to the synchronized block will be blocked intil the lock the first thread holds on the block of code is released.
Bosun
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13064
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Any request to the servlet will spawn a new thread a separate copy of a servlet will be running is that true ?"
NO - the same copy of the servlet object will be shared by all Threads. That is why you must be very carefull about using instance variables - they are visible to all Threads.
If you can't figure out a way to share a resource, you can synchronize access. Synchronizing the entire method is safest. If you synchronize a block, be sure to synchronize on an object that is visible to all Threads - synchronizing on a local object is useless.
Bill
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by William Brogden:
If you can't figure out a way to share a resource, you can synchronize access.

... or implement SingleThreadModel.
- Peter
 
Val Dra
Ranch Hand
Posts: 439
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i needed a way to control doGet method so i won't leave it. so using synchronized block was a good idea for me. I still want the servlet to be multi threaded. Thanks for your input.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic