Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are static class variables stored in memory?

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.

like image 625
tskuzzy Avatar asked Jul 11 '11 19:07

tskuzzy


3 Answers

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.

like image 183
bdonlan Avatar answered Nov 14 '22 16:11

bdonlan


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.

like image 40
antlersoft Avatar answered Nov 14 '22 15:11

antlersoft


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.

like image 1
satish reddy Avatar answered Nov 14 '22 16:11

satish reddy