Garbage Collection (GC) in Java is the process of automatically managing memory by removing unused objects to free up memory for new ones. It is handled by the Java Virtual Machine (JVM).
Key Points:
- Automatic Process: No need to explicitly deallocate memory.
- Unreachable Objects: GC removes objects no longer referenced by the program.
- GC Methods:
- System.gc(): Requests GC, but it’s not guaranteed to run immediately.
- Runtime.getRuntime().gc(): Similar to
System.gc()
.
How it Works:
- Mark and Sweep Algorithm: Marks objects in use and clears those unmarked.
- Generations:
- Young Generation: Short-lived objects (e.g., temporary variables).
- Old Generation: Long-lived objects.
- Permanent Generation (Pre-Java 8): Metadata about classes.
Benefits:
- Prevents memory leaks.
- Simplifies memory management for developers.
Example:
- Note: Garbage Collection is not deterministic and depends on the JVM.