Memory management in Java
2 types of memory
1) Stack
2) Heap
Stack memory:
---Stores temporary variables and separate memory block for methods.
--- Store primitive data types
--- Store Reference of heap objects.
1) Strong reference
2)Weak references
3)Soft references
---- Each thread has its own stack memory.
---- Variables within a scope is only visible and as soon as any variable goes out of the scope it will get deleted in LIFO order in stack.
NOTE: Primitive variable doesn’t hold any reference.
---Heap Memory is always larger than stack
Heap memory:
Store objects
There is no order of allocating the memory.
---- Garbage collector is used to delete the unreferenced objects from the heap memory Mark and sweep algorithm
Types of GC
1) Single GC
2)Parallel GC
3)CMS(Concurrent Mark sweep)
4)G1
---Garbage collector will delete the unused objects in the heap memory
---heap memory is shared with all the threads
---Heap also contains the string pool.
---When Heap memory goes full, it throws “Java.lang.OutofememoeyError”
---String literals are stored in string pool which is in heap memory. (The reference of this string literals and other object references in heap memory are stored in stack memory).
Heap memory is divided into two parts
--- Young generation ---> Young generation is divided into three parts 1) Eden 2)so 3)s1.
---Old generation
There is another space not in heap memory known as metaspace
Metaspace : it is outside the heap memory It stores the class variables, for ex : constants, static final.