Garbage collection in java

Let’s learn garbage collection in java.

Garbage collection in java

Garbage collection means destroying or de-allocating unused objects in memory.

Objects which are not used or has no references can be reclaimed.

garbage collection in java

Garbage collector is used to reclaim unused memory automatically.

Java handles memory de-allocation automatically since object once created uses some memory in the heap location.

How it works?

Before java, most popular programming language was either C or C++.

So if you know these languages you would know that you are supposed to manage your own memory in those languages.

Also read – major features of java

For example, in C you have methods like calloc(), malloc() and realloc() that would allow buffer memories for you.

You have to specify how much memory you need for your program and say that in those API calls and then can get you a buffer of memory for doing something like creating a linked list node or something like that.

But at the end of your program, at some logical point you are responsible for freeing that memory as well.

So, let’s imagine a big application written in C language that keeps on allocating buffer memories and sometimes it forgets to free the memory and eventually they’ll cause memory leaks and lot of issues in the application.

Also read – learn methods in java

Also in C++ you would use constructors like new and destructors to release resources.

So those are some things that programmers had to take care or worry about whenever they were implementing these things in languages like C and C++.

But java came with a automatic memory management through a thread called garbage collector and its primary objective is to free heap memory by destroying unreachable objects.

Garbage collector is one of the daemon thread which runs always in the background.


What are unreachable objects in java?

When an object becomes eligible for garbage collection?

Unreachable objects are those objects which do not have live references. Let’s see an example,

public static void main(String[] args)
{
   // StringBuffer object sb is not eligible for garbage collection
   StringBuffer sb = new StringBuffer("Flower Brackets");
   System.out.println(sb);
   // StringBuffer object sb is eligible for garbage collection
   sb = null;
}


In the main method I have created StringBuffer object and its reference. I’m going to print this StringBuffer object.

At this stage StringBuffer object is not eligible for garbage collection. Now I’m going to assign value “null” for StringBuffer object.

In this case StringBuffer object is eligible for garbage collection and becomes unreachable object in the heap memory.

So, it basically works on a couple of hypothesis which is, that most of the objects soon become unreachable.

That means the objects are generally created in context of “if block” or a method.

So most of the objects are created like that to write your code and those objects are out of scope as soon as the method execution is complete, those can be garbage collected.

Next is references from old objects to new objects only exists in small numbers.

That means, objects that live for long time in your application doesn’t generally refer to newly created objects.

Here are couple of terms that we should be familiar with; one is “live” object. Live object is an object in your application that is referred by another object in your application.

Also read – java overview

Another is “dead” object. Dead object is unreachable object which is created during a method call and as soon as the method call is over the object became out of context and just lying there in heap.


When is an object eligible for garbage collection?

If an object doesn’t have any reference variable then object is eligible for garbage collection.


How to make an object eligible for garbage collection?

Below are few ways,

  • null reference variable

Student obj = new Student();

obj = null;

  • re-assign reference variable

Student obj1 = new Student();

Student obj2 = new Student();

obj1 = obj2;

  • create anonymous object

new Student();


After making object eligible for garbage collection, object do not destroy immediately by garbage collector.

Also read – preface to java virtual machine and architecture

But when java virtual machine runs garbage collector then only object is destroyed.

NOTE: garbage collector collects only objects created using “new” keyword and for objects without “new” keyword use finalize() method.


There are two methods to request java virtual machine to run garbage collector. They are,

  1. System.gc() method
  2. finalize() method
  3. Runtime.getRuntime().gc() method

Static method gc() is found in System class. This method requests JVM to invoke garbage collector.

Let’s see java program on gc() method invoking garbage collector.

public class GarbageCollector
{
   public static void main(String[] args)
   {
      Employee obj1 = new Employee();
      Employee obj2 = new Employee();
      obj1 = null;
      obj2 = null;
      System.gc();
   }
   public void finalize()
   {
      System.out.println("object garbage collected");
   }
}


Output:

object garbage collected

object garbage collected


finalize() method is called just before object is destroyed. This method is defined in Object class:

protected void finalize() throws Throwable

  • Finalize method is used to close database connection.
  • This method is called by garbage collector not JVM.
  • We have to override finalize() method. Because it has empty implementation.
  • It is invoked only once per object.

getRuntime().gc() method is present in Runtime class. getRuntime().gc() method returns the Runtime object associated with the current Java application.

Let’s see java program on getRuntime().gc() method.

public class Demo
{
   public static void main(String[] args)
   {
      Demo obj1 = new Demo();
      Demo obj2 = new Demo();
      // nullifying reference variable
      obj1 = null;
      // nullifying reference variable
      obj2 = null;
      // running Garbage Collector
      Runtime.getRuntime().gc();
   }
   @Override
   protected void finalize() throws Throwable
   {
      System.out.println("Garbage collector called");
      System.out.println("Object garbage collector: " + this);
   }
}


Output:

Garbage collector called
Object garbage collector: Demo@2130772
Garbage collector called
Object garbage collector: Demo@cd4e940


Advantages of garbage collection:

  1. Garbage collection in java happens automatically, since java relieves you from additional burden of releasing used memory. Hence making java memory efficient.
  2. Garbage collection ensures program integrity.
  3. We don’t have to write extra code since garbage collector is the part of JVM.

what is the purpose of garbage collection in java and when is it used

As we discussed earlier the purpose of garbage collection is to destroying or discarding unused objects in a java application.

Please read above section to know when is it used.


This is about garbage collection. Garbage collection in java is the most asked interview questions.

I’ll keep this post updated with new versions of java.