Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dont declare global variables in Servlet

 
D.R.Vinayak
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,
This is really interesting,don't declare global variables in Servlet or Action Servlet.If you declare Name as a global variable , if user 'A' log's in and set his Name in the variable ,in the mean time if user 'B' log's in and set his name in variable,then user 'A' will have same value in global variable as that of 'B'.Reason,Container always creates a new thread for every request,this thread only execute service method,so the global variables are global for all the user..So avoid using global variables in Servlet...
If i m not right please correct me...according to my observation i faced this problem in my application and overcome by removing global variable.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What are you calling global variables ? Static variables ?
 
Atul Sawant
Ranch Hand
Posts: 304
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vinayak,

Kindly illustrate an example for us?

Regards
 
D.R.Vinayak
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When user log's in to our system we used to save his information like first name last name etc.we used global variable for that,since we are using that variables across different function,Now suppose user 'A' logs in his information will be saved in this variables,im mean time if user 'B' logs in his information will be over ridden so ,user who logged in first will loose his information,and his name will change to that of 'B'
 
D.R.Vinayak
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
not static variable
 
Adithya Menon
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
instance variable are shared by all the threads.unlike the localvariables they are not thread safe.
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They are NOT global variables but instance variables. As they are available to any thread and for every request there is a new thread, the chances are high to have an ambiguity on the variable's value.

Instead you can have a local variable in either of doGet() or doPost() method which are definitely threadsafe since every thread will get its own copy.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic