Garbage Collection in Java
Garbage Collection (GC) is the process in programming languages like Java where the runtime environment automatically manages the memory by reclaiming and recycling memory occupied by objects that are no longer in use or accessible by the program. This process is crucial to prevent memory leaks and optimize the use of the available heap memory.
In languages like Java, memory is dynamically allocated when objects are created using the new keyword. However, once an object is no longer referenced, it becomes eligible for garbage collection because it is no longer reachable or needed by the application.
Purpose of Garbage Collection
The primary purpose of garbage collection is to free up memory that is no longer in use, preventing memory leaks and ensuring efficient memory utilization. This helps maintain the performance and stability of Java applications.
Key Concepts of Garbage Collection:
- Heap Memory:
Java divides memory into several regions. The heap is where objects are stored, and it is divided into:
- Young Generation: Where new objects are created. This is further divided into Eden and two survivor spaces (S0, S1).
- Old Generation (Tenured Generation): Where long-lived objects that survive garbage collection cycles in the Young Generation are moved.
- Permanent Generation (Metaspace in Java 8+): Contains metadata and class information.
2. Garbage Collection Process:
- Mark: The garbage collector identifies objects that are reachable and marks them.
- Sweep: The GC reclaims memory occupied by unmarked (unreachable) objects.
- Compact (Optional): After sweeping, the memory may be fragmented, so the GC might compact the memory to avoid fragmentation and allow contiguous space allocation for new objects.
3. GC Algorithms:
- Serial GC: A simple garbage collector used for small applications.
- Parallel GC: Uses multiple threads for GC and is used for high-throughput applications.
- Concurrent Mark-Sweep (CMS): A low-latency collector that runs concurrently with the application.
- G1 GC (Garbage First): A balanced collector designed for large heap sizes that partitions the heap into regions and works in parallel.
4. Generational Garbage Collection:
- Objects are divided based on their age into generations.
- Young Generation: Where most objects are initially allocated. Short-lived objects are collected during minor garbage collections.
- Old Generation: Holds long-lived objects. Major garbage collection happens here when objects survive several rounds of minor collection.
- Minor GC: Collects objects from the Young Generation.
- Major GC: Collects objects from the Old Generation.
- Permanent Generation (PermGen): Used to store metadata about classes and methods. In Java 8 and later, this has been replaced by the Metaspace, which is not part of the heap and is managed differently.
5. Garbage Collection Tuning
Garbage collection can be tuned to optimize performance based on the specific needs of an application. Some common tuning parameters include:
- Heap Size: Adjusting the initial and maximum heap size using
-Xmsand-Xmxoptions. - Garbage Collector Selection: Choosing the appropriate garbage collector using options like
-XX:+UseSerialGC,-XX:+UseParallelGC,-XX:+UseConcMarkSweepGC,-XX:+UseG1GC, etc. - Pause Time Goals: Setting pause time goals using options like
-XX:MaxGCPauseMillis.
6. Finalization
Java provides a mechanism called finalization, where objects can define a finalize method that is called before the object is garbage collected. However, this mechanism is generally discouraged due to its unpredictable nature and potential performance issues.
7. Weak, Soft, and Phantom References
Java provides different types of references that allow more control over object lifecycle:
- Weak References: Objects that are only weakly reachable are eligible for garbage collection.
- Soft References: Objects that are only softly reachable are eligible for garbage collection but are less likely to be collected than weakly reachable objects.
- Phantom References: Used to track when an object is about to be garbage collected, allowing for cleanup actions without preventing the object from being collected.
|---------------------- Java Heap -----------------------|
| |
| |----------------- Young Generation ----------------| |
| | | |
| | |--- Eden Space ---| |-- S0 --| |-- S1 --| | |
| | (New objects here) (Survivor Spaces) | |
| | | |
| |-----------------------------------------------------| |
| |
| |--------- Old Generation ---------| |
| | | |
| | (Long-lived objects) | |
| | | |
| |---------------------------------| |
| |
| |-------------- Metaspace (PermGen) --------------| |
| | | |
| | (Class Metadata, Method Area) | |
| | | |
| |-------------------------------------------------| |
| |
|---------------------------------------------------------|Detailed Steps of Garbage Collection:
- Object Creation: When an object is created, it is stored in the Eden Space.
- Minor Garbage Collection: As objects are created, the Eden Space may fill up. A minor GC is triggered, moving surviving objects to one of the survivor spaces (S0 or S1). The rest are discarded.
- Promotion to Old Generation: Objects that survive multiple rounds of minor GC are moved to the Old Generation.
- Major Garbage Collection: When the Old Generation fills up, a major GC is triggered. This is a more time-consuming process as the GC needs to clean up objects that have survived for a long time.
- Compact (Optional): If memory fragmentation occurs, the GC might compact the heap to create contiguous space.
Advantages of Garbage Collection:
- Automatic Memory Management: Developers do not need to explicitly manage memory, reducing the chance of memory leaks or invalid pointer errors.
- Prevents Memory Leaks: Unused objects are reclaimed automatically, optimizing memory usage.
Disadvantages:
- Performance Overhead: Garbage collection introduces pauses in the application during the GC process, which can lead to performance degradation, especially in real-time or low-latency applications.
- Limited Control: Developers have limited control over when and how garbage collection occurs, though tools like
System.gc()allow some intervention.
When does an object become eligible for garbage collection?
- No active reference: An object becomes eligible for garbage collection when it is no longer reachable from any live thread or active part of the program.
- Cyclic references: Java’s garbage collector can handle cyclic references (e.g., two objects referencing each other) as long as they are not reachable from the program’s root.
👏 If you found my articles useful, please consider giving it claps and sharing it with your friends and colleagues.
To read other topics






