Middle
Tell us about memory areas and garbage collector operation in Java.
sobes.tech AI
Answer from AI
In Java, the Java Virtual Machine (JVM) manages several memory areas:
- Heap: A shared area for all application threads. Objects and arrays are stored here. The heap size is determined by JVM settings. The garbage collector operates in the heap.
- Stack: Memory area for each thread. Stores local variables of primitive types and references to objects in the heap. The stack size is fixed or dynamically adjustable depending on JVM settings.
- Method Area: Stores per-class structures (runtime constants pool, field and method data, code for methods and constructors). In newer Java versions, it is merged with Metaspace.
- Metaspace: A non-heap memory area that stores class metadata. Its default size is unlimited (depends on available memory).
- Program Counter Register: Points to the JVM instruction currently being executed. Each thread has its own.
- Native Method Stack: Supports calls to native (non-Java) methods.
Garbage Collector (GC) is an automatic memory management process in the heap. It frees memory occupied by objects that are no longer referenced, preventing memory leaks.
Main stages of GC operation:
- Marking: GC determines which objects are reachable from root elements (e.g., references from thread stacks, static variables). Other objects are considered unreachable.
- Sweeping: GC frees memory occupied by unreachable objects.
- Compacting: Some garbage collectors move reachable objects to eliminate memory fragmentation.
GC operates based on the concept of generations (Generational Garbage Collection):
- Young Generation: Area for new objects. Most objects die quickly, so GC runs frequently and fast here.
- Eden Space: Area where new objects are created.
- Survivor Spaces (S0, S1): Objects that survived GC in Eden are moved here. Objects are moved between S0 and S1 after each collection.
- Old Generation: Area for objects that have survived several collections in the young generation (passed a certain "age"). GC runs less frequently but longer here.
- Permanent Generation: In older Java versions, stored class metadata and static data. Replaced by Metaspace.
Different GC implementations (G1, CMS, Serial, Parallel, ZGC, Shenandoah) use various algorithms for marking, cleaning, and compacting, optimized for different scenarios.