• Post Reply Bookmark Topic Watch Topic
  • New Topic

Multithreading in Servlets

 
amit sanghai
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do we have to do so that the web server handles concurrent requests from different clients?
does the web container handle that by concurrent execution of the service method on different threads OR do we have to do something?
 
Andy Bowes
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your Web server will automatically handle multiple simultaneous requests to servlets without you needing to do any work.
Simplistically, the web-server will load a single instance of the servlet when it is first invoked and then each service() method is executed on it's own thread.
[NB - You can break this if you declare instance variables in the servlet that are then modified within the methods used to service the request so you need to be a bit careful]
 
amit sanghai
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so, there might be synchronization issues or inconsistency. How is that handled?
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65530
105
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The same way you would deal with concurrency issues in any other class.
Firstly, as Andy pointed out, instance variables should be avoided. Other threading techniques, such as the declaration of critical sections (via the synchronized keyword) to protect against race conditions, should be employed.
Perform a search on 'threading' or 'threads' in these forums. There's a lot of good information to be had.
hth,
bear
[ May 02, 2003: Message edited by: Bear Bibeault ]
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just a few rules to avoid interference between "simultaneous" requests.
1. Never use servlet instance variables to store stuff that changes with each user. Instead use the session capabilities provided by the servlet container (servlet engine - as Tomcat).
2. Use local variables declared inside your doGet or doPost - they are automatically Thread-safe.
3. If you absolutely have to have a single instance of a resource that all requests share, use synchronized methods to ensure that only one request uses the resource "at one time".
4. Never try to hang on to the request and response objects provided by the servlet container - they must be managed by the container.
Be prepared to learn new coding habits - the web application environment is a big change from the single-user application environment.
Bill
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!