Originally posted by carl chan:
Sorry guys, I understand that the jsp is same as implemenets SingleThreadModel, but i don't understand why the three instance are sharing the same variable "j", I think the code <%! int j=0; %> already reset j=0 when ever a new instance was created. Isn't it true?
In case of SingleThreadModel, the container has two options. It can
a) either create only one instance of the servlet, queue the incomming requests, and then dispatch them one by one. When the servlet is servicing the first request other requests in the queue are blocked. The container can opt for this method if there are relatively few requests and blocking may not affect the response time.
b) or create multiple instances, one for each request. In this case, the requests are being serviced simultameously by different instances and are not blocked. The container can opt for this method if there are two many requests and blocking may affect the response time.
For example, the container may decide to queue 10 requests per instance. If 10 clients hit the servlet simultaneously, then the container may create only one instance, service the first request and block the other 9. However, if 50 clients hit simultaneously, then the container may create 5 servlet-instances with 10 requests in each servlet's queue.
Later, when the number of requests reduce to say, less then 10, the container can call destroy() on the other four instances and pull them out of service.
In your case, the container is creating only one instance. Hence, the first request-thread increments j from 0 to 9, then the second request from 10-19, etc. If it had created three instances, you would have got 0-9 for each thread.
Note that in either case, one-instance (#a) or multiple-instances (#b), "thread-safety" of the individual instance(s) is guaranteed. This means, in the above example, you will never see the output from two requests mixing the values as
UserA - 0,1,2,9,10,11,...
UserB - 3,4,5,12,13,14,...
UserC - 6,7,8,15,16,17,...
Hope that help
-j