Monday, January 6, 2025
HomeProgrammingGarbage Collection in Java

Garbage Collection in Java

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:

  1. Automatic Process: No need to explicitly deallocate memory.
  2. Unreachable Objects: GC removes objects no longer referenced by the program.
  3. 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.
See also  Software Design Patterns Tutorial

Benefits:

  • Prevents memory leaks.
  • Simplifies memory management for developers.

Example:

java
public class GarbageCollectionExample {
public static void main(String[] args) {
String str = new String("Hello");
str = null; // Eligible for garbage collection
System.gc(); // Suggest garbage collection
}
}
  • Note: Garbage Collection is not deterministic and depends on the JVM.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x