JVM Memory Management

The instructions of a running program and the related data are temporarily stored in the computer memory. Java has good news for you here: you don’t need to worry about memory management because the JVM and garbage collector will take care of it. However, you can help by being aware of where different things are stored in the memory. This will also help you to understand how objects are created. As shown in Figure below, a program’s data is placed in two different areas in memory: the stack and the heap. Stack and heap refers to the different ways to store the elements of a running program in memory.




Stack Memory

The following elements of a Java program live on the stack:

• Local variables: The variables of primitive types defined inside a method or as method parameters.


• Local reference variables: The variables that refer to an object and are defined inside a method or as a method parameter. Remember that an object that a local variable refers to lives on the heap and not on the stack.


• Method invocations: When you invoke (call) a method, the method is pushed onto the stack (that is, placed on top of the stack). Local variables live inside a method, and the scope of a local variable is the execution of the method. When the method execution is complete, the local variables inside the method are gone. But the objects, to which some of these local variables may be referring, are still alive and well on the heap.

Heap Memory

The following elements of a Java program live on the heap:

• Instance variables: The variables of primitive types defined inside a class but outside of all its methods.


• Instance reference variables: The variables that refer to an object and are defined inside a class but outside of all its methods.


• Objects: Represent the entities in the real-world problem that the Java program is trying to solve. All the objects live on the heap, always.


Remembering whether a particular element lives on the stack or on the heap is easy: a local variable (primitive or reference) belongs to a method and lives with it on the stack, while an instance variable belongs to an object and lives with it on a heap. However, also note that a local reference variable on a stack points to an object on the heap, and the object will not die with the local reference variable. 

The objects on the heap that are no longer in use are eventually collected by a program called a garbage collector to free up the memory used by them. For this reason, the heaps are also called garbage-collectible heaps

No comments:

Post a Comment