Where are static class variables stored in memory? - java

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.

Related

Does a static variable go on the permanent gen space on the heap

If I create a static variable in Java, does it automatically go into the perm gen space on the heap? it seems obvious that the answer is yes, but i cannot find the confirmation anywhere.
I know the static variable (also strings and enums) are alive for the life of the JVM so it must go on the permanent heap. IS this correct?
The idea of the "PermGen" is completely implementation-dependent, and JVMs are free to handle the "physical" memory management however makes sense to them--they're not even actually required to provide garbage collection!
The PermGen is just a feature of some JVM implementations (including the Sun/Oracle HotSpot JVM for many years), and it's actually being eliminated with a new approach in the Oracle Java 8 JVM. It's quite likely that JVMs that include the concept of a PermGen will put static variables there for performance, but it's entirely up to the programmer.
JLS #17.4.1 Shared Variables
Memory that can be shared between threads is called shared memory or heap memory.
All instance fields, static fields and array elements are stored in heap memory. In this chapter, we use the term variable to refer to both fields and array elements. Local variables (§14.4), formal method parameters (§8.4.1) or exception handler parameters are never shared between threads and are unaffected by the memory model.
Nice description here By #Stephen:static allocation in java - heap, stack and permanent generation

In Java, is there a way to track if a variable, a method or a class created in Heap or Stack?

I am trying to fully understand how the Java works with its memory arrangement. The discussions on Internet are very confused, and sometimes contradicts each other, so I found no one I can trust. This thing can be very complicate if it mixed with static, static method, local variable, thread, volatile and so on. So I am thinking if there is a way I can study that myself my doing some Java coding experiment. A class MemoryTrack does something like this,
public myMethod(){
int i = 0;
MemoryTrack.show(new myClass()); //print out "Heap at address 111"
MemoryTrack.show(new myClass()); //print out "Heap at address 222"
MemoryTrack.show(i); //print out "Stack at address 333"
MemoryTrack.show("a static method"); //print out "stack at address 444"
}
The use of memory is described in Section 2.5 of the Java Virtual Machine Specification. The stack stores stack frames (containing local variables and partial results). The heap is where all class instances and arrays come from. Stack frames can also be allocated from the heap (and then pushed onto the stack). There are also method areas and runtime constant pool memory. The details are spelled out in the spec.
As far as monitoring memory usage, several profilers have tools for that. For monitoring from within the program, take a look at the MemoryMXBean class (and related classes in the java.lang.management package). It's very easy to use. While it probably doesn't give you everything that it sounds like you want, but it's probably the best thing available.
The rule is pretty simple: heap contains objects, stack contains local variables and method parameters. Object fields are inside the objects, in the heap. Don't know about static fields. Methods and constructors are not stored in the stack, nor in the heap. Threads and volatile don't matter.
Method calls are on the stack. Each has a space reserved to it, the stack frame, that contains the local variables and the parameters.
Two things you need to know
its not as complicated as you think.
it doesn't matter 99% of the time.
Variables are always on the stack.
Objects are always on the heap. (There are exceptions but I wouldn't worry about them)
Methods and classes are always in the perm gen.
In the HotSpot/OpenJDK JVM, static fields are collected in a singleton object for the class. You can see the instance if you do a heap dump. Other JVMs may do this differently.
A class MemoryTrack does something like this,
Such a method wouldn't do anything useful as the argument will always be on the stack and object it refers to will always be on the heap. You can't get the memory location of an Object in a standard way and it unlikely to be useful if it did as it can change at any time.
You may think all variables in Java are on heap. Actually it is implementation dependent.

where the memory allocated when we declare static? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
static allocation in java - heap, stack and permanent generation
its a small confusion...defining static to class, methods and variables.In this three cases where thus the memory allocated. ? My boss is familiar with C,he says only variables are in heap memory and rest (static classes and static methods) will remain in main memory. is that ture? any explanation.?
one more
in android using static class and static methods is a best practice ?
Try this,
static members are stored in Method Area.
Class instances and arrays are stored in heap memory. Heap memory is also called as shared memory. As this is the place where multiple threads will share the same data.
Non-heap Memory
It comprises of ‘Method Area’ and other memory required for internal processing. So here the major player is ‘Method Area’.
Method Area
As given in the last line, method area is part of non-heap memory( A special heap area). It stores per-class structures, code for methods and constructors. Per-class structure means runtime constants and static fields.
The above three (heap memory, non-heap memory and method area) are the main jargon when it comes to memory and JVM.
Class instances and arrays are stored in heap memory. Heap memory is also called as shared memory. As this is the place where multiple threads will share the same data.
Static variables are saved in the same place as the Classes declaration (methods and attributes, etc). 1). Classes (loaded by the classloaders) go in a special area on heap called Permanent Generation, and static field too go to the same place as they are common to each instance of the class.
For more details :
see this answer

Static Method Memory Allocation

We have two classifications heap and stack . When a object is created, memory for object is stored in heap. What if the class has static methods ,which can be called using class name. If object is not created then how will it allocate memory and if it does where will it allocate memory?
It depends on the JVM, but static fields are usually stored in a special object on the heap. (You can see it in a heap dump) When the ClassLoader is unloaded, its classes and their static "objects"/fields are also cleaned up.
The only thing different about the static "object" is you can't get a reference to it. (But you can use reflection to access the fields)
Methods (i.e., code) aren't stored in an object; all objects of a class will share the code for a method. Regardless of language (Java, C++, or virtually anything else) there will be only a single copy of the code for any method, static or not. Generally there's a specific area of memory -- i.e., a CODE segment in a native language like C++, or a special heap area in Java -- where code is loaded.
Permanent Generation(PermGen) space of heap contain permanent class
metadata and descriptors information.
PermGen space always reserved for classes and those that are tied to
the classes(Static members, static functions, etc...)
Static function belongs to the class so they can be called to without
creating the object of the class.

why use Heap Memory in Java

Why do we use Heap Memory, Can we use Stack memory for the same?
EDITED
One more question came in my mind after reading answers
1) is there any other kind of memory which we can think of alternative to Heap and Stack?
Edited
I came across the string pool, is that memory associated with the heap or Stack?
Well, you have to use the heap if you want to use objects. Objects are inherently pointers on the stack (or inside other objects) to memory chunks in the heap.
Unlike C++ where you can put objects on the stack or heap, Java does things differently.
Even in C++, it's a good idea to use the heap for objects that must outlive the function they were created in. You probably can avoid it but you may find yourself with a performance problem with all the copy constructors.
As to your edit:
Is there any other kind of memory which we can think of alternative to Heap and Stack?
Sure there is: Static data members, the ones where there's only one per class rather than one per instantiated object must go somewhere. These can't be on the stack since they may disappear when you exit from a function. And they can't belong to an particular object.
These (at least in the Sun/Oracle JVM) go into the Method area.
In addition, you should not think of there being one stack. Every thread gets its own stack on creation.
There's also the runtime constant pool and stacks for native (non-Java) calls.
There's lots of information on the JVM internals here regarding that aspect but keep in mind there may be a distinction between the logical machine and the implementation.
Heap memory is central to Java. All objects are allocated on the heap, and local variables hold only references (essentially pointers) to them. C# allows you to have objects (value types) that live on the stack. Java chose not to borrow this from C++, partly in order to simplify the language.
Across languages, heap memory is the way to provide long-lived objects of arbitrary size.
Can we use Stack memory for the same?
Basically no.
In Java, stack memory is used solely for parameters and local variables of methods (and some hidden book-keeping info which is not relevant to this discussion). And for those variables, only primitive types use just stack memory. Any object or array is represented as a reference to something on the heap, and Java provides no way to allocate an object or array on the stack.
[Aside: it is theoretically possible to perform any calculation in Java using just primitive types and recursive static methods. However, it would be horribly messy. Even writing a simple message to the console will entail your application causing objects to be allocated on the heap. So we can dismiss this as being totally impractical.]
In the JVM, instead of a thread local stack for objects it uses a Thread Local Allocation Buffer or (TLAB) This gives much of the performance benifits of a Stack, without the developer needing to worry about wether an object is on the stack or not.
Heap memory is used to store objects in Java. No matter, where object is created in code.
e.g. as member variable, local variable or class variable, they are always created inside heap space in Java.
If there is no memory left in stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError,
While if there is no more heap space for creating object, JVM will throw
java.lang.OutOfMemoryError Java Heap Space.
Another important factor to consider is scoping. If all objects were to be allocated on stack then they go out of context as stack frame gets rolled out. In layman terms, think of stack as a dump that stores all the variable values and object references that are local to a subroutine/method which is currently in scope. As soon as it finishes executing (or the method goes out of scope), then all in it would be lost.
It makes it easier for compiler to manage large &/or dynamic sized variables too- they still take small constant storage on call stack- that of 4 bytes ( a heap pointer).

Categories