• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Multi-threaded servlet

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Guys,
Consider the below code of a multithreaded servlet.
public class test extends HttpServlet
{
private int xx;

public void init(ServletConfig config)
throws ServletException)
{
xx=0;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
xx= xx + 1;
do something here....
dothis();
out.println(xx);
}
private void dothis()
{
long processing here... take a break first...
}
Suppose client1 accesses the servlet, upon entry to the servlet's doPost() method it increments the xx variable by 1 then calls the dothis() method. While client1 is on dothis() method, client2 accesses the same servlet thereby increasing xx's value by 1 again. By the time, client1 reaches the "out.println(xx);" client1's xx value is already 2, when by right it should be 1 only.
I remedied this problem by adding "synchronized", or implementing the servlet as a SingleThreadedModel. But this makes my servlet less efficient if there are many users accessing the same servlet at the same time. Will making my servlet multithreaded make it behave like a CGI application. In CGI's, each client has its own memory space, have its own set of variables, thus multiple clients can access the same CGI w/o affecting each other. How do i implement a multi-threaded servlet? pls provide details (links to src codes if possible). thanks.
Jonathan
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The basic answer is DONT USE INSTANCE VARIABLES! Local variables are fine because each Thread has its own copy.
Servlets are intrinsically multi-thread safe IF you provide for making shared data multi-thread safe.
public synchronized int incXX(){ return ++x ; }
In your example, your doGet should keep a local copy of the incremented xx value.
int localX = incXX();
Bill

------------------
author of:
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I was under the assumption client1 and client2 will get its own set of instance variables. Then int xx which is initialized to 0 for all the new instances, then it should increment on that.
Some one shed some light on these. Thanks
 
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
init() method is invoked only once when the server is started and subsequent invocation of doGet() does not involve the init() method.
i hope i am right. please do correct me if i am wrong.
sagar
 
William Brogden
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"I was under the assumption client1 and client2 will get its own set of instance variables. Then int xx which is initialized to 0 for all the new instances, then it should increment on that.
Some one shed some light on these. Thanks"
Your assumption is exactly wrong. With normal servlets there is only one instance - thats what makes servlets so fast, you don't have to create a new instance for every request.
However, there is a way to insure that requests do not share an instance. Servlets that implement the SingleThreadModel interface are handled differently by servlet engines - only one Request per instance, the engine is free to either limit access to a single instance or create multiple instances. This approach is only for extreme cases.
(Yes, init is only called once, when the instance is first created.)
Bill

------------------
author of:
 
shyam nagarajan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Validate these points
So Servlet Engine implements Singelton Pattern, meaning it ensures only one Instance runs at a time.
so in that case, should the methods in the servlets be synchronized so as to avoid multithread corruption of data?
Or in other words how does the doget method maintains state of each request? Hope this questions make sense? I am tring to find out how the order of execution takes place in multithreaded environment.
 
William Brogden
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"so in that case, should the methods in the servlets be synchronized so as to avoid multithread corruption of data?
Or in other words how does the doget method maintains state of each request?"
It requires a major change in viewpoint to get this, but once you are there it all makes sense. I'm going to have to try this in pseudo code - lets suppose you are making a chat servlet - here is the servlet flow:

1) is this request from a new user? (determine by cookie or hidden form variable)
Yes -> create new ChatState object and store it somewhere indexed by user's id. (possible storage: database, hashtable, HttpSession object)
No -> recover old ChatState object
Note - the ChatState object is a local variable in the doGet or doPost method - only saving and recovering the ChatState object needs to be synchronized. HttpSession does this automatically.
2) Carry out request - record changed status in ChatState object
3) If the user is leaving you can destroy the old ChatState, otherwise it hangs around in an HttpSession or Hashtable or whatever.
(I hope that makes sense)
Bill
 
reply
    Bookmark Topic Watch Topic
  • New Topic