Middle+
How is memory organized in JVM?
sobes.tech AI
Answer from AI
The JVM memory is divided into the following data areas:
- Heap: The memory area where class objects and arrays are stored. It is shared among all threads. Managed by the garbage collector. It consists of generations (Young, Old, Permanent/Metaspace).
- Stack: The memory area for each JVM thread. Stores local variables, method parameters, and frame information for each method call. When a method finishes, its frame is removed from the stack.
- Method Area: Stores class metadata: bytecode of methods, constant pool, static variables. In older JVM versions, it was called Permanent Generation; in newer versions (Java 8+), it has been replaced by Metaspace.
- PC Registers: For each JVM thread. Stores the address of the next JVM instruction to execute.
- Native Method Stacks: Store calls to native (non-Java) methods. Use the native libraries invoked by the application.
Memory management in the Heap is handled by the garbage collector (GC). It automatically frees memory from objects that are no longer referenced.
Example of working with Heap and Stack:
// Object 'obj' is created in the Heap.
Object obj = new Object();
// Local variable 'i' is stored in the thread's Stack.
int i = 10;
public void myMethod(int param) { // Parameter 'param' is in the Stack of this method frame.
// Local variable 'local' is in the Stack of this method frame.
String local = "hello";
// A new object is created in the Heap. The reference to it is in the Stack of this method frame.
MyClass myObj = new MyClass();
}
Difference between Heap and Stack:
- Heap: Shared among all threads, stores objects, managed by GC.
- Stack: Belongs to a single thread, stores primitives and object references, managed by method frames.
Memory management in JVM includes:
- Allocation of memory when creating objects.
- Deallocation of unused objects' memory (garbage collection).
- Optimization of memory usage.