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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With