• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread-safe global variables

 
Ali Ekber
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone pls tell me how to declare thread-safe global variables in a servlet? Thanks.
 
Sharad Agarwal
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could make their access thread-safe by adding synchronization.
 
Ali Ekber
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But if you declare the variables in the synchronized block, they will be local varibles. If you declare it out side the synchronized block, will they be thread-safe, even if you assig values inside the synchronized block? Thanks.
 
Sharad Agarwal
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ali Ekber:
But if you declare the variables in the synchronized block, they will be local varibles. If you declare it out side the synchronized block, will they be thread-safe, even if you assig values inside the synchronized block? Thanks.


The amswer to your last question is 'yes'. Please allow me to elaborate. Add synchronization blocks around the code that accesses the variables, and not the declaration. The declaration remains global (class member variable). But, when the variable is accessed, we force the different threads to stand in line and do their thing in sequence.
 
Ali Ekber
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah! Now I got it. Thanks alot!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic