Garbage Collection in Java

  • May 28, 2022
  • Java
user-defined exception

Garbage collection is the method through which Java programs maintain their memory automatically.

working:

  • Java programs are compiled into bytecode that may be executed by a Java Virtual Machine, or JVM.
  • Objects are produced on the heap, which is a part of memory dedicated to the Java application, while it runs on the JVM.
  • Some objects will become obsolete over time.
  • The garbage collector detects these useless objects and deletes them to free up memory.
The Benefits of Garbage Collection:
  • The garbage collector removes unreferenced objects from heap memory, making Java memory efficient.
  • We don’t have to do anything because the garbage collector (part of the JVM) does it.
Ways to make an object unreferenced :

There are numerous options:

  • Nullifying a reference
  • Assigning a reference to someone else
  • By anonymous item, and so forth.
Nullifying a reference:
Student s=new Student();  
s=null;  
Assigning a reference to someone else:
Student s1=new Student();  
Student s2=new Student();  
s1=s2;//now the first object referred by e1 is available for garbage collection  
By anonymous item:
new Student();  
finalize() method:


Before the object is garbage collected, the finalize() function is called. This strategy can be used to tidy up your data. This method is defined as follows in the Object class:

protected void finalize(){}  

Some Key Points to Keep in Mind:

  • It is specified in the java.lang package.
  • Because it is an object class, it is accessible to all classes.
  • Inside the Object class, it is declared as protected.
  • A Daemon thread called GC (Garbage Collector) thread calls it only once.
gc() method:


The garbage collector is called using the gc() method, which performs cleanup operations. The gc() method is available in the System and Runtime classes.

public static void gc(){}  
Simple example of garbage collection:
public class TestGarbage1
{  
 public void finalize()
   {
     System.out.println("object is garbage collected");
    }  
 public static void main(String args[])
 {  
    TestGarbage1 s1=new TestGarbage1();  
    TestGarbage1 s2=new TestGarbage1();  
    s1=null;  
    s2=null;  
    System.gc();  
   }  
}  
Output:
object is garbage collected
object is garbage collected

Note: also read about this keyword in Java

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

Your email address will not be published. Required fields are marked *