This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
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

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
Pie
Posts: 49733
69
  • 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
Pie
Posts: 15436
41
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