Tuesday, December 28, 2021

Java Memory

 As developer its important to know how memory works in java, its helps code optimization. Here we will learn how to manage memory in java.


Java memory split in to two section 


The stack and the Heap.


Stack is widely used memory, all the primitive types other than String are stored in stack, values stored in stack is not shared across the JVM because every thread have its own stack. Java exactly knows when the data on the stack be destroyed. We all know that stack is First In Last Out, so very time its create a data in a stack it will be the top of the existing data. For example, in below code

    int age = 12;

    int height = 100;

    String name = "User";

Data of the age variable is stored in stack at first on the top, then height variable is created on the stack on top of the age, then the name reference is create in stack on the top of the height variable.

                                



In the above stack image we can see the primitive values are stored in stack, but the String reference only saved in stack, where the data of String is getting saved, yes its getting saved in heap memory.

Heap 

Data allowed in heap will be live longer than stack, because there only one heap per application, so the data saved in heap will be shared with other method or function across the application. 


Here I add some code snippet for collection object. I am adding list of string in List object, and then printing the string calling other method. Below code up to line number 12, we are adding string in list called stringList. 





Above image stringList reference is stored in stack and all data in the list is saved in heap List and each string stored in separately. Since Line 10 and 12 we are adding "One" to the list, so index 2 of  list will use existing string One.                                                                                                                              

Let see what happen if we execute lien 13, calling a method from main method. Here jvm will create a new thread for new method call getList().                                                                                                  




If you see the above image stringList is out of scope. Because the current thread is running getList() until line 22 execute stringList is out of scope. After Line 22 execute stringList will be on visible, see the below image                                                                                                                                      

stringList has 3 string in it before execute getList(), after execution of getList() the stringList having 4 string in it. Because of getList method works on copy of reference of  value of the stringList.    
    
Are you confused with pass by value and pass by reference, check below post there I explained clearly.

2 comments: