Junior
What is garbage collection in Java?
sobes.tech AI
Answer from AI
Automatic memory management process that removes unused objects from the heap, freeing up the space they occupy. The Garbage Collector (GC) determines which objects are accessible (referenceable) from the running parts of the program and which are not (unreachable), and deletes the latter.
Main stages:
- Marking: GC identifies which objects are alive (reachable) starting from roots (e.g., local variables of active threads, static variables).
- Sweeping: GC traverses the heap and removes all objects not marked as alive.
- Compacting (optional): Moves live objects to reduce memory fragmentation.
Advantages:
- Simplifies development by eliminating manual memory management.
- Reduces the risk of memory leaks and dangling pointers.
Disadvantages:
- Pauses may occur during garbage collection (Stop-the-World events).
- GC requires computational resources.
Various garbage collection algorithms (Serial GC, Parallel GC, CMS, G1, ZGC, Shenandoah) differ in performance, latency, and memory usage.
// Example of a memory leak where GC cannot free objects
import java.util.ArrayList;
import java.util.List;
public class MemoryLeakExample {
private List<Object> list = new ArrayList<>();
public void addObject(Object obj) {
list.add(obj); // Objects are added to the list and remain accessible
}
public static void main(String[] args) {
MemoryLeakExample example = new MemoryLeakExample();
for (int i = 0; i < 1000000; i++) {
example.addObject(new Object()); // Each new object is added to the list
}
// The list example.list holds references to all created objects,
// preventing their garbage collection, even if the example object
// ceases to be accessible from main (in this case, example lives until the end of main).
// In more complex scenarios, if the instance of MemoryLeakExample
// remains accessible due to some external reference,
// then all objects in the list will be retained.
}
}