Wednesday, 24 January 2018

Garbage Collection

What is Garbage Collection?

Garbage Collection (GC) is the process by which the JVM automatically frees up memory by removing objects that are no longer in use. It runs in the background along with the Java program, reclaiming unused memory to improve the performance of applications.

Ways to Make an Object Eligible for Garbage Collection : 
  1. Nullifying the reference variable
  2. Reassign the reference variable
  3. Objects created inside a method

·    1. Nullifying the reference variable : 
  • If an object is no longer required, we can make it eligible for Garbage Collection by assigning null to its reference variables.
  • Student s1 = new Student();
    s1 = null; // Now eligible for GC



2.Reassign the reference variable :
  • If a reference variable is reassigned to point to another object, the old object becomes unreachable and eligible for Garbage Collection.
  • Student s1 = new Student();
    Student s2 = new Student();
    s1 = s2; // Old s1 object is now eligible for GC
· 



3.Objects created inside a method :
  • Objects created inside a method are eligible for Garbage Collection once the method completes, provided there are no references outside the method.
  • void myMethod() {
        MyClass obj = new MyClass();
        // obj is eligible for GC after method execution
    }
class MyClass { int id; MyClass(int id) { this.id = id; System.out.println("Object " + id + " created"); } // finalize() is deprecated after Java 9, // but here we use it only for demonstration @Override protected void finalize() throws Throwable { System.out.println("Object " + id + " is garbage collected"); } } public class GCDemo { public static void main(String[] args) { createObject(); // Requesting JVM to run GC System.gc(); // Adding delay to give GC some time try { Thread.sleep(1000); } catch (InterruptedException e) {} System.out.println("End of main method"); } static void createObject() { MyClass obj = new MyClass(1); // After this method ends, 'obj' goes out of scope // and becomes eligible for Garbage Collection } } 
 class MyClass {
    int id;

    MyClass(int id) {
        this.id = id;
        System.out.println("Object " + id + " created");
    }

    // finalize() is deprecated after Java 9, 
    // but here we use it only for demonstration
    @Override
    protected void finalize() throws Throwable {
        System.out.println("Object " + id + " is garbage collected");
    }
}

public class GCDemo {
    public static void main(String[] args) {
        createObject();
        
        // Requesting JVM to run GC
        System.gc();

        // Adding delay to give GC some time
        try { Thread.sleep(1000); } catch (InterruptedException e) {}
        
        System.out.println("End of main method");
    }

    static void createObject() {
        MyClass obj = new MyClass(1);
        // After this method ends, 'obj' goes out of scope
        // and becomes eligible for Garbage Collection
    }
}

Explanation :

  1. Inside createObject()

    • obj is a local variable referring to a MyClass object.
    • When the method finishes, the variable obj goes out of scope.
      2. After method execution
    • No references to that object remain.
    • Hence, the object becomes eligible for Garbage Collection.
3.System.gc() call

  • Requests JVM to run the GC.
  • If the JVM runs GC, the overridden finalize() method is called, and you’ll see:
  • Object 1 is garbage collected 

⚠️ Note: finalize() is deprecated in modern Java, but it is still useful for demonstration purposes to see when GC happens. In real-world code, use AutoCloseable or try-with-resources for cleanup. 



Ways for requesting JVM to run Garbage Collector :

Although you cannot force garbage collection, you can request it using the following methods:

Using System.gc(): System class contains a static method GC for this.
  • Example : System.gc();                                        

System.gc() method is used to call the garbage collector to perform clean-up processing.

Using Runtime.getRuntime().gc() : Runtime class is a singleton class present in java.lang. Package. We can create Runtime object by using factory method getRuntime().
Exam[le : Runtime.getRuntime().gc();               
👉 Note: Both methods (System.gc() and Runtime.getRuntime().gc()) are equivalent. However, the JVM is not obligated to perform garbage collection immediately.

Ques : Can the Garbage Collection be forced by any means?
Ans  : No. Garbage Collection cannot be forced.You can only request it, but there is no guarantee that the JVM will execute it at that moment.

Finalization(⚠️ Deprecated):
  • Before destroying an object, the Garbage Collector once invoked the finalize() method to perform cleanup activities.
  • The finalize() method is defined in the Object class:
  • @Override
    protected void finalize() throws Throwable {
        // cleanup code
    }    
⚠️ Note: Starting from Java 9, the finalize() method has been deprecated, and it is strongly discouraged to use it. Developers should use alternatives like try-with-resources or implement AutoCloseable for cleanup tasks.

Memory leak: 

A memory leak occurs when an object is no longer needed by the application but is still referenced, preventing it from being collected by the Garbage Collector.

This leads to unnecessary memory consumption and can cause the application to slow down or crash.

No comments:

Post a Comment

Java Development Kit (JDK) and Java Runtime Environment (JRE)

                  Java Development Kit (JDK) and Java Runtime Environment (JRE)  To download and install the Java Development Kit (  JDK ) ...