JVM defines various runtime data areas which are used during execution of a program. Some of the areas are created by the JVM whereas some are created by the threads that are used in a program. However, the memory area created by JVM is destroyed only when the JVM exits. The data areas of thread are created during instantiation and destroyed when the thread exits. These areas include:
Heap is a shared runtime data area where objects and arrays are stored. It is created when the JVM starts.
new keyword is used the object is allocated in the heap and its reference
is stored in the stack.
Scanner sc = new Scanner(System.in);
Here, the Scanner object is stored in the heap and the reference sc is stored in the
stack.
Note: Garbage collection in heap area is mandatory.
java.lang.OutOfMemoryError.Note: Though method area is logically a part of heap, it may or may not be garbage collected even if garbage collection is compulsory in heap area.
class Geeks {
// static variables are stored in the Method Area
static int v = 100;
// instance variables are stored in the Heap
int i = 10;
public void Display()
{
// local variables are stored in the Stack
int s = 20;
System.out.println(v);
System.out.println(s);
}
}
public class Main {
public static void main(String[] args) {
Geeks g = new Geeks();
// Calling the Display method
g.Display();
}
}
java.lang.StackOverflowError occurs in
Java.
Note:
System.gc(), but the JVM ultimately
decides when it should run.
In Java, an object consists of three main parts:
| Parameter | STACK | HEAP |
|---|---|---|
| Basic | Memory is allocated in a contiguous block. | Memory is allocated in any random order. |
| Allocation and De-allocation | Automatic by compiler instructions. | Manual by the programmer (in C or C++ and garbage collector in Java or Python) |
| Cost | Less | More |
| Implementation | Easy | Hard |
| Main Issue | Shortage of memory | Memory fragmentation |
| Locality of reference | Excellent | Adequate |
| Safety | Thread safe, data stored can only be accessed by the owner | Not Thread safe, data stored visible to all threads |
| Flexibility | Fixed-size | Resizing is possible |
| Data type structure | Linear | Hierarchical |
| Preferred | Static memory allocation is preferred in an array. | Heap memory allocation is preferred in the linked list. |
| Size | Smaller than heap memory. | Larger than stack memory. |
My simple library
..of useful code