• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What will be the output of this servlet?

 
Deep Krishna
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a servlet as follows. When i execute this servlet (each client request is in different browser), will the result (value of j for each client) predictable. Assuming non-distributable environment.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet implements SingleThreadModel
{
int i = 0;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
int j = ++i;
out.println(j);
}
}

thanks
deep
 
Johannes de Jong
tumbleweed
Bartender
Posts: 5089
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The values would be different. To test it simply start your browser up multiple times
 
Kyle Brown
author
Ranch Hand
Posts: 3892
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe the answer is no it's not predictable. Remember that each request is a separate thread. Since the getting and incrementing of i is not synchronized it is possible (not likely, but possible) for odd things to happen like one thread incrementing i a second time before j is printed.
The moral of the story is NEVER update instance variables in servlets! Servlet variables should only be read-only.
Kyle
------------------
Kyle Brown,
Author of Enterprise Java (tm) Programming with IBM Websphere
See my homepage at http://members.aol.com/kgb1001001 for other WebSphere information.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Deep,
Since you are using the SingleThreadModel for your servlet, you won't have any synchronisation problems. Anyway, the results predictability only depends on the container and whether you are using a pool of instances or only one intance. In case of one instance, it will be predictable.
I also agree with Kyle, that it is never a good idea to update instance variables inside a servlet, because of two problems:
- forces synchronisation
- prevents the use of a pool of instances for handling requests
Cheers,
Beno�t
 
Kyle Brown
author
Ranch Hand
Posts: 3892
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good point Benoit. I completely missed that he was using SingleThreadModel (sound of hand slapping forehead). In that case it will be deterministic as you say.
------------------
Kyle Brown,
Author of Enterprise Java (tm) Programming with IBM Websphere
See my homepage at http://members.aol.com/kgb1001001 for other WebSphere information.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic