13
votes

This is a follow-up question to How are static arrays stored in Java memory? .

So global variables in C/C++ are stored in the static data segment of memory. But what about static class variables in Java/C++?

It can't be the static data segment because you don't know what/how many classes are going to be referenced throughout the duration of your program (because of reflection). It's definitely not the stack because that makes no sense. Storing it on the heap is also kind of iffy.

3
Is this a C++ or a Java question? In C++ static members are just global variables. - Kerrek SB
@Kerrek: I believe he is wondering about Java memory management of static that mimics C/C++ management of similar concepts. - user7116
@Six: Sure. I just found "what about static class variables in Java/C++" a bit confusing. I look forward to the Java-related answers. By the way, does Java have an explicit "heap"? - Kerrek SB
I guess I'm asking about both C++ and Java. C doesn't have objects so how memory is laid out is pretty simple. For objects, instance variables are stored on the heap. However what I don't understand is where class variables are stored. - tskuzzy
In C++ the situation is simple because there is no (portable) way to load a class at runtime. In C++ class static data members are just global variables with a fancy name, they are created when program starts and destroyed when programs end... exactly like globals. - 6502

3 Answers

5
votes

In Java, at a low level, class static variables are indeed stored on the heap, along with all other class metadata. To Java, they look like globals, but to the JVM's low level heap management routines, they're dynamic data (although they may be treated slightly specially in order to improve GC efficiency, since they're likely to be long lived). After all, classes can be unloaded by unreferencing their classloader.

As for whether it's the same as the C malloc(), not likely. Most JVMs take control of their heaps at a low level; they grab a chunk of memory from the OS and divvy it up themselves. As such, most Java data, including static data, are not stored in the malloc heap, but rather in a separate heap managed by the JVM.

3
votes

Java has a "permanent" heap where it puts class metadata. So the "roots" of the static values are in the permanent heap. The values are reference values (class objects) the values themselves are in the regular heap.

1
votes

Static variables will not be stored in Heap.. They are part of Data Segment. Local variables will be stored in - Stack; Instance variables will be stored in - Heap; Class variables(Static) will be stored in - Data Segment. These variables will be shared across all objects of that class.. Your final machine equivalent java code will be stored in - Code/text segment.