Middle
Are there any links that demonstrate the work of a garbage collector?
sobes.tech AI
Answer from AI
Yes, it is possible to create examples demonstrating the impact of the garbage collector.
// Example 1: Creating a large number of objects
public class GarbageCollectionDemo1 {
public static void main(String[] args) {
List<DummyObject> objects = new ArrayList<>();
for (int i = 0; i < 1000000; i++) {
objects.add(new DummyObject(i)); // Creating many objects
}
// At this point, the garbage collector may be invoked to free memory
// if the objects in the list are no longer used elsewhere.
// Even if not explicitly called, it will run when needed.
// Clearing the list potentially frees memory
objects.clear();
System.gc(); // Explicit request for garbage collection (not guaranteed to execute)
}
static class DummyObject {
private int id;
public DummyObject(int id) {
this.id = id;
}
@Override
protected void finalize() throws Throwable {
// The finalize method is called before garbage collection (not guaranteed and not recommended)
// System.out.println("Collecting object with id: " + id);
}
}
}
// Example 2: Nullifying references
public class GarbageCollectionDemo2 {
public static void main(String[] args) {
Object obj = new Object(); // Creating an object
System.out.println("Object created.");
obj = null; // Removing the reference to the object. It is now eligible for garbage collection.
System.out.println("Reference to object set to null.");
System.gc(); // Explicit request for garbage collection
}
}
These examples demonstrate how creating many objects or removing references makes objects available for garbage collection. It is important to understand that calling System.gc() does not guarantee immediate garbage collection; the JVM decides when to run it based on its internal algorithms.