• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Local Vs. Global - Results

 
Paul McKenna
Ugly Redneck
Ranch Hand
Posts: 1006
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi..
I wrote the following servlet and tested it
public class MyServlet extends HttpServlet {
....
public int j = 0;
public void doGet(HttpServletRequest req, HttpServletResponse res) {
int k = 0;
System.out.println("J : "+j);
System.out.println("K : "+k);
i++;
k++;
}
}
As expected, K remained constant at 0 and J kept increasing.
Then I made the servlet implement Single Thread Model, hoping to see both remain as 0. However this did not happen. Any explanations why? As far as I can see.. since a new servlet instance is created, I should also remain as 0.
Thanks in advance.
SR
 
Nancy King
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try to use private int j = 0; instead of public int j = 0;

Nancy
 
Yu Chen
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not sure what is the purpose for this testing. But changing it to private should not make any difference, it only changes the access scope, since the incremens are within a instance method, it won't make any difference.
The container can either do sequence processing of the requests or has a pool instance of this servlet, but in either case, the values of j & k should be changing.
Another point is that the container is going to create multiple instances of this servlet, it would make more sense to make j a static variable than a instance variable.
 
Maha Annadurai
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This statement "but in either case, the values of j & k should be changing." in above reply is not correct.
Only J will be incremented for subsquent requests. K will not be incremented , since it is a local var and each request gets a fresh initialized copy each time it enters the service(req,res) -->doGet(req,res) methods.
Regards,
Maha Anna
 
k space
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then I made the servlet implement Single Thread Model, hoping to see both remain as 0. However this did not happen. Any explanations why? As far as I can see.. since a new servlet instance is created, I should also remain as 0.

Implementing SingleThreadModel does not necessary to create a new instance. It only guarantees that no two threads will execute concurrently in the servlet's service method.
The servlet container may synchronize accesses to a single instance, or maintain a pool of instances.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic