File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes static variables in multithreading Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "static variables in multithreading" Watch "static variables in multithreading" New topic

static variables in multithreading

gaurav abbi
Ranch Hand

Joined: Jan 05, 2007
Posts: 108
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..

thanks,<br />gaurav abbi
Ricky Clarkson
Ranch Hand

Joined: Jul 27, 2006
Posts: 131
They live on the heap.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
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

Joined: Aug 16, 2005
Posts: 15082

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).

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Rahul Bhattacharjee
Ranch Hand

Joined: Nov 29, 2005
Posts: 2308
static variables live on the heap.

Rahul Bhattacharjee
LinkedIn - Blog
I agree. Here's the link:
subject: static variables in multithreading
It's not a secret anymore!