Sunday 2 April 2017

Java Memory Model

Java memory model plays important role to check knowledge of candidate under category of JVM architecture. Sound knowledge of memory model helps programmer to write memory efficient code with less memory leakage. It also plays very important role when we do write code for multi threaded environment.


1. Explain memory model of Java in brief?

Answer: Java memory model consists of following parts:
1. Heap: It stores the objects that has been created by application.
2. Stack: It stores method calls , local variable and local references.
3. Method Area: It stores details of class(in binary form).Execution environment of Java refer method area to run the program. 
4. Class Loader: It contain class loader library and responsible for loading classes and interfaces. It is not consider as part of memory model, In fact It is part of JVM architecture. 
5. Program Counter(PC): It stores next instruction need to execute.

Note: Please note that above mentioned categories is just a logical structure, At physical level we have RAM and Local Cache. So there is a mapping in place between logical structure and physical structure. 


2. Discuss Heap in detail?

Answer: Heap is the area which stores objects created by application in execution. Heap is divided into following categories:

Fig: Java Heap Memory
1. Eden space : It stores the newly created object. This is the storage area of all the novice objects.
2. S0 (Survivor stage) : It stores the objects which survive after early GC cycles. Objects promote to S0 once they survive early GC cycles.
3. S1 (Survivor stage) : It stores the objects which survive after early GC cycle. Objects are moved to S1 once they survive early GC cycles.
Eden space and Survivor space(S0 and S1) combined called Young generation. JVM perform only minor GC on Young generation. 
4. Old generation : It stores the objects which survive for long time(many minor GC cycles) and at this stage Major GC need to run to acclaim the memory.
5. Permanent generation : It contain pools(like String pool) and information related to classes and methods.
All threads in Java share same Heap memory. Whatever Java stores on heap belongs to all the threads.

Note: Please note that Permanent generation is no longer part of Java memory model from Java 8. Permanent generation has replaced by Meta Space in Java 8 because of it's limitation of  being fixed in size and can not grow at run time as per the situation. Famous Java Perm space error is because of this limitation only.


3. Discuss Stack in detail?

Answer: Stack is limited ans small size memory area which stores following details:
1. Primitive local variable: Value and reference both store in stack.
2. Local references of objects: Only references store in stack actual object lies in heap only.
3. Method calls: All the method calls go into stack.
Each thread in Java has it's own Stack memory. One thread can not access Stack of other thread. Whatever Java stores on Stack belongs to only owner thread of that Stack.

Follow-up question 1: How memory allocation will take place in below code?

1
2
3
4
5
6
7
8
public class StackExample {
 String s1;
 void show(){
  String s2 = new String("Local"); 
  s1 = new String("Global");
  int a = 2;
 }
}

Answer: 1. Object created at Line 4 and 5 will store at Heap memory.
2. Local primitive  variable "a" and it's value 2 will store at Stack memory and it won't be share by threads , Each thread will get it's own copy of "a" in their Stack memory.
3. Local reference variable "s2" will also store at Stack memory and it also won't be share between threads.
4. Global reference variable "s1" will store at Heap along with object of StackMemory class hence it will shared by all the threads.
Please refer below figure (Assume above code is running by two threads).
Fig : Memory Allocation

Note: In above code s2 is thread safe since each thread has it's own object and there own reference whereas s1 is shared by both the thread hence any modification by one thread will impact other thread.

Follow-up question 2: What will be output of below code?

1
2
3
4
5
6
7
8
9
class StackExample{
 public static void main(String[] args) {
  StackExample example = new StackExample();
 }
 
 public StackExample(){
  new StackExample();
 }
}
Answer: StackOverflowError.

If you notice at line number 7 we are creating new object and for that we are making call to constructor. If you look carefully at code you will notice that we are making recursive call to StackExample() constructor without terminal condition i.e. infinite loop. As a fact we know that constructor are nothing but special kind of method in Java. So calls to constructors will also store in Stack(as mentioned in Question 3 that Stack stores all method calls).


From all the facts mentioned above we can conclude that each time we make call to constructor  at line number 7 it will get store in Stack,.Our program running in infinite loop ad Stack is small in nature so at one point of time stack will be full and will run out of memory which will eventually trigger StackOverflowError.



4. What is Perm Gen space error?

Answer: Permanent generation was part of non-heap memory till Java 7. It stores loaded class, class metadata and method information etc. Size of Permanent generation need to set(-XX:PermSize) at the start of JVM and once set it can not grow itself and throws error(Perm Gen space) if more memory required for storage of class metadata and other information.

Designer of Java has decided to get rid of Permanent generation and they replaced it by Meta space in Java 8.
Meta space is separate memory area and grow-able in nature. Since Meta space is grow-able in nature hence no more Perm Gen space error from Java 8.

5. What is different types of GC (Garbage collection)?

Answer: Majorly there are two types of GC:
1. Minor GC: Java performs minor GC on Young generation. It start from eden space when eden space is about to getting full. After minor GC some objects survive and move to Survivor stage S0 or S1 depends on settings(Survivor stage allocation ration) of JVM.
Minor GC runs on survivor stages too in order to claim memory.
2. Major GC: Java performs major GC on Old generation. Major GC is very rare in compare of minor GC and it is also time taking process.
Java's garbage collection uses Mark and Sweep algorithm in which It first mark all the objects which are eligible for GC and then acclaim those memory one by one.

6. Stack/Heap is thread safe or not?

Answer: Heap is not thread safe since Heap space shared by all the Threads.Stack is thread safe since each thread has it's own Stack memory.
Let's discuss the code and memory allocation diagram mentioned in question 3. Reference variable s1 which stored at Heap along with object of StackExample. At line number 5 Thread 1 created new object and assign it to s1, later thread 2 created new object at line number 5 and assign it to s1 again. It means s1 is not thread safe since it is shared by both the thread. 
We can conclude easily that Heap area is not thread safe and we need to place extra care(synchronization, volatile etc.) for data stored at heap.
While in case of Stack each thread got their own Stack memory. Both the thread will have their own s2 reference variable pointing to two different object. 
We can conclude that all the data stored in Stack are by default thread safe and doesn't require any extra care.

7. How you will decide max and min size of Heap for your application?

Answer: There is no hard and first rule for deciding max and min size of Heap. It all depends on your application. Best way to find right value is by analyzing your application memory usage using any of the memory profiler tools.

It always recommended that you choose your max heap value very carefully. If you provide very high value for max heap to fix or avoid OutOfMemory error. it will definitely fix your OutOfMemory problem but it will create another problem for you that is major GC, Major GC will have to cover large memory area because you have given very high value for max heap which will eventually slow down your application during Major GC cycle. 
It always recommended that choose your max and min value carefully by analyzing your application's memory footprints.


8. What is memory leak?

Answer: Memory leak is a case when GC not able to claim(or simply not able to recognize) memories of objects even those objects are no longer required by application. They are unused object but some how GC fails to identify them. Hence these objects live in memory for long time and unnecessary waste the memory which can be utilize otherwise.
Now question arises, How GC identifies unused object? There are few objects that is defined as root objects some example like current method in execution's local variable, input parameters, global variables etc. These root objects never consider for GC.
So GC simply try to find all the object which can be reachable from these root object rest of all unreachable objects are eligible for GC.

No comments:

Post a Comment