Java Garbage Collection and Finalize Class

 Garbage collection

  • Garbage which indicates unreferenced objects/variables.
  • It is the process of destroying unreferenced objects.
  • It is performed automatically, providing better memory management.
  • If our heap memory is flooded with objects, it will start the garbage collection from the older objects.
  • We can also do the garbage collection manually by using the finalize() and gc() methods.
  • The finalize() method invokes before an unreferenced object is removed.
  • The gc() is used to invoke the garbage collector to perform its operation.
  • The gc() method is basically found at the system and runtime.


Finalizer methods

• The finalize() method is called the finalizer.

• The main purpose of a finalizer is, however, to release resources used by objects before they're removed from the memory.

• A finalizer can work as the primary mechanism for clean-up operations, or as a safety net when other methods fail.


Example 01:

package GarbageCollection;


public class ex1 {


public void finalize() {

System.out.println("Object in the garbage collection");

}

public static void main(String[] args) {

ex1 ex = new ex1();

ex1 exobj = new ex1();

ex=null;

exobj=null;

System.gc();

}

}


Example 02:

package GarbageCollection;


public class GarbageCollectionExample {

public static void main(String[] args) {

GarbageCollectionExample obj1 = new GarbageCollectionExample();

GarbageCollectionExample obj2 = new GarbageCollectionExample();


// Assigning obj2 reference to obj1, making obj1 reference eligible for garbage collection

obj1 = obj2;


// Making obj2 reference null, making obj2 eligible for garbage collection

obj2 = null;


// Requesting garbage collection explicitly

System.gc();


// Printing a message to indicate that the objects have been garbage collected

System.out.println("Garbage collection has been requested.");


// Adding a delay to observe the garbage collection process

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}


// Overriding the finalize() method to print a message when the object is being garbage collected

@Override

protected void finalize() throws Throwable {

System.out.println("Object is being garbage collected: " + this);

}

}










Post a Comment

0 Comments