[To advertise Java(tm) Events here, contact!]

by example!

New @

  gb  In-house search engine for better results!

  gb  Get updates with the

 Browse Categories 
 Ask a Java Question 
  For Java Tips & Tricks, subscribe to the newsletter!
Search Java Q&A, Links, API's:   adv 

What is the difference between the Serlvet single threaded model and multi threaded model?
Typically, a servlet class is instantiated the first time it is invoked. The same instance will be used over several client requests, so all members that are declared in that servlet are shared accross clients. That is what is meant by multi threaded model, multiple clients that access the same instance.

There are situations where you want to protect your servlet member variables from being modified by different clients. In this case, you can have your servlet implement the marker interface SingleThreadModel. Every time a client makes a request to a servlet that implements this interface, the engine will create a new instance of the servlet. For performance reasons, the engine can also maintain a instance pool, handing out instances as they are needed. Or it could also serialize client requests, executing one after another.

To see the differences in action, check out the following servlets.

MultiThread Servlet

Open up two browser instances, have both of them point to . The servlet code is simple. It saves some state in a variable, sleeps for 10 seconds and finally checks if that state has been changed during its nap. Since this is a multi threaded model servlet, the second client will change the internal state of the servlet. The first servlet is confused after its snooze.

The code for this servlet can be found below.

SingleThread Servlet

Again, open up two browser instances, have both of them point to The code is the same as in MultiThread, except that it implements the marker interface SingleThreadServlet. Now notice that the state of the first client is not affected by the second client.

This code sample is only viewable to members
Login or become a member!

This code sample is only viewable to members
Login or become a member!

Further Information
Author of answer: Joris Van den Bogaert

Comments to this answer are only viewable by members. Login or become a member!

Terms of Service | Privacy Policy | Contact

Copyright © 2000-2003 - All Rights Reserved 
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. is independent of Sun Microsystems, Inc. All other trademarks are the sole property of their respective owners.