Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

scope of servlet variables

 
sean cee
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
let's say we have the following:
public class refresh extends HttpServlet {
private int oCounter = 0 ;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
int iCounter = 0 ;
blah....
}
What is the scope of oCounter and iCounter?
It seems like iCounter dies after the request leaves the servlet.
whereas oCounter servives throughout the session.
Am I right?
If so, can using many of the "global" servlet variable throughout the application be resourse demanding ?
Thanks in advance.

 
Tim Holloway
Saloon Keeper
Pie
Posts: 18098
50
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you have the lifetimes correct. No, using global variables isn't going to demand lots of resources, but this is in part because generally there's only one instance of the servlet - your problem is going to be maintaining the integrity of global variables in a multi-threaded environment!
 
James Hobson
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Scope in a Servlet is just the same as anywhere else except that app servers do pooling and other strage tricks to confuse you.
You seem to be correct -- and class level variables could be a resource problem, but most seriously they are thread-unsafe -- unless you are very careful you may find all kinds of strange results.

James
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The lifetime of oCounter is certainly not "session". The session is associated with a single client, and survives as long as the client keeps talking to the site (roughly). Your counter, on the other hand, is visible to all clients, and lives as long as the servlet itself (which may be a second, a year, whatever; it's up to the application server to decide).
- Peter
 
jayram
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I dont see why the Class level variable cause resource problems. Yes but they are thread unsafe (provided you are not following SingThreadModel)
As to variables that are local to the doGet/doPost methods they have local lifespan so for each client request a new copy of these gets created.
------------------
What if this is as good as it gets ?
 
sean cee
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys for all your comments
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic