Java Memory Management
Heap Memory:
Used for dynamic memory allocation for Java objects and JRE classes at runtime.
Divided into two main regions: Young Generation and Old (or Tenured) Generation.
Young Generation: Newly created objects are allocated here. It is further subdivided into Eden Space, Survivor Space S0, and Survivor Space S1.
Old Generation: Long-lived objects are eventually promoted to this space.
Garbage Collection: The process of automatically freeing memory by deleting unreachable objects.
Stack Memory:
Used for method execution and contains local variables and method call details.
Each thread has its own stack, which is not shared with other threads.
Method Area:
Stores class-level information such as metadata, constants, static variables, and the code for methods.
Program Counter (PC) Register:
Holds the address of the currently executing instruction of a thread.
Native Method Stack:
Used for native methods (methods written in languages other than Java, like C/C++).
2. Garbage Collection (GC)
Garbage Collection is the process of automatically reclaiming memory by deleting objects that are no longer reachable in the program.
Types of Garbage Collectors:
Serial Garbage Collector: Suitable for small applications with a single-threaded environment.
Parallel Garbage Collector: Also known as the throughput collector, it uses multiple threads to speed up garbage collection.
CMS (Concurrent Mark-Sweep) Garbage Collector: Focuses on low-latency applications and attempts to minimize pause times.
G1 (Garbage-First) Garbage Collector: Aims to replace CMS with predictable pause times and improved performance.
Garbage Collection Phases:
Mark: Identifies which objects are still in use and which are not.
Sweep: Deletes objects that are not marked.
Compact: Optional phase that defragments the heap memory by moving live objects together.
OutOfMemoryError: When the JVM runs out of heap space.
Performance Degradation: As the garbage collector has more objects to process.
public class GarbageCollectionExample {
public static void main(String[] args) {
GarbageCollectionExample gc = new GarbageCollectionExample();
gc = null;
// Requesting JVM to run Garbage Collector
System.gc();
System.out.println("Garbage Collection executed");
}
@Override
protected void finalize() throws Throwable {
System.out.println("Garbage collected object");
}
}In this example, the finalize() method is called when the garbage collector determines that there are no more references to the object. The System.gc() method is a request to the JVM to run the garbage collector, though it is not guaranteed that the garbage collection will happen immediately.