• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instance variables of the servlet

 
Danish Shaukat
Ranch Hand
Posts: 341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all !
A single servlet instance creates a new thread for every client request.So there can be danger of simultaneous access to instance variables.
So do you think that it is a good idea to keep all the variables as local variables i.e in the doGet/doPost methods.
I'm a little confused on this.
Regards
Danish
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13071
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. Actually the servlet engine typically re-uses Threads, but as you say, instance variables will be "simultaneously" visible to many request processing Threads.
2. Any variable that changes with each request should NOT be an instance variable in the servlet class. You can use local variables, variables attached to a session, etc. - If you have more than a few variables that carry user specific data, consider making a utility class to keep track of the data. For simple servlets, a session is usually sufficient.
Bill
 
Cory Wilkerson
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, is this on a per client basis here or are you suggesting that a single servlet instance is created by the servlet engine to process all clients/all requests? I'm not familiar enough with the servlet specification to argue otherwise, it's just always been my assumption that a unique instance of a particular servlet was created on a per client basis (not on a "per request" basis).
Just looking for some clarification -- and thank you.
 
Cory Wilkerson
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After reading the Servlet spec...I stand corrected. So, I'm assuming that when JSP developers declare variables throughout the page, they're method local to doPost/doGet once the servlet is compiled?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13071
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whether or not a JSP variable is an instance variable or a local variable depends on where and how it is declared. If you are experimenting with JSP, take a look at the generated java files, it is very instructive.
You will also find the JSP specs very informative.
Bill
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic