Welcome to our comprehensive guide on Java Garbage Collection! In this lesson, we'll dive deep into understanding what garbage collection is, why it's essential, and how it works in Java. We'll also provide practical examples to help you grasp the concepts better. Let's get started!
In simple terms, garbage collection is a process that automatically frees up memory in Java by removing unused objects. This is crucial because Java uses a dynamic memory allocation system, which means it allocates memory during runtime. Over time, unused objects can accumulate, causing a slowdown in performance or even memory leaks. Garbage collection helps prevent this.
Java provides several types of garbage collectors, but we'll focus on the two most common ones:
public class GarbageCollectionExample {
public static void main(String[] args) {
Object obj1 = new Object(); // Create an object
System.out.println("Object created");
// Create a strong reference to the object
Object obj2 = obj1;
// Let's assume obj1 is no longer needed
obj1 = null;
// Wait for garbage collection to run
System.gc();
// Check if the object is still in memory
if (obj2 != null) {
System.out.println("Object still in memory");
} else {
System.out.println("Object has been collected by garbage collector");
}
}
}In this example, we create an object obj1, create a strong reference obj2 to it, and then set obj1 to null. We trigger garbage collection using System.gc() and check if the object is still in memory.
What is the purpose of Java's garbage collector?