This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static variables in multithreading

 
gaurav abbi
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
as we know instance variables live on heap inside the object, but where do static variables live. if they live on stack, then different threads have different stacks, so in that case do they have different copies of static variables or is there some sharing mechanism going on.

please correct me if my understanding is wrong..
 
Ricky Clarkson
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They live on the heap.
 
Campbell Ritchie
Sheriff
Posts: 48442
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As far as I know a static member of a class is loaded into memory whenever the class is loaded and remains there. So there is only ever one copy of each static member in memory.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With static member variables there is only one copy of the variable that is shared by all threads - not one copy per thread.

If you need one copy per thread, then you can use class java.lang.ThreadLocal (look it up in the API documentation).
 
Rahul Bhattacharjee
Ranch Hand
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
static variables live on the heap.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic