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