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

Instance variables

 
Chris Brat
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have read that it is never a good idea to declare static variables (because of the huge number of servlets that can access the same variable at the same time), and that if they are used they should be declared as final...
my question is whether it is accepted to declare instance variables or should values that are required rather be kept in the session or passed as parameters (ex. between doGet method and doPost in the same servlet).
I know this is most definitely a silly question, so please be gentle in your responses.
Thanks.
 
Neeraj Singhal
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Chris
The instance variables in the servlets are shared by all the threads accessing it. Hence, if one thread changes the value, it will be reflected by all th threads.
So, its better to put such varaibles in session, that are specific to a client.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static final should be fine for something that you want to share among all instances and all threads, maybe configuration stuff. "final" is important because you promise the compiler you'll never change the value and the compiler enforces the promise.
If values change in member variables, you have to be careful to synchronize access. Something as simple as

could have unpredictable results because of other threads. There may be times you want to do this ... maybe a configuration variable can be changed via an administrative function. For example, an admin might turn logging on and off.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic