简体   繁体   中英

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM