Garbage collection in java

Let’s learn garbage collection in java.

garbage collection in java

What is garbage collection in java?

Garbage collection means destroying/de-allocating unused objects in memory. Objects which are not used or has no references can be reclaimed.

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 section.

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 – java features

For example, in C you have methods like calloc(), malloc(), 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 method 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 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.

Also read – preface to java virtual machine and architecture

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.

So those are the unreachable objects.


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?

There are few ways,

  • null reference variable

Student obj = new Student();

obj = null;

  • 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. But when java virtual machine runs garbage collector then only object is destroyed.

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

  1. gc() method
  2. finalize() method

Static method gc() is found in System and Runtime 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.

Advantages:

  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.