×

Java Garbage Collection

Java Garbage Collection

In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the Java Garbage Collection is used to destroy the reference less or unused objects. In this section, we are going to discuss what is garbage collection in Java.

What is Java Garbage Collection?

  • Java garbage collection is a feature used in Java that releases the runtime unused memory by destroying the unreferenced objects.
  • To achieve the same in C, one has to use the free() function, and the delete() function is used in C++.
  • But in Java, the garbage collector runs automatically while the program is in execution.
  • The garbage collector resides inside the JVM (Java Virtual Machine).

However, in Java, the garbage collection is done automatically. Hence, Java has better memory management as compared to C and C++.

Why Java Garbage Collection is required?

In languages like C++, it is the responsibility of the programmer to create as well destruct the objects. Many times, it is observed that the programmer created the objects but forgot to destruct the objects. Because of this negligence, at the specific point of time, there will be a shortage of memory for the creation of more objects, and this may lead to abnormal termination of the program because of OutOfMemoryErrors. Hence, to get rid of such errors, Garbage Collection is introduced in Java, that works automatically and does the destruction of unreachable or reference less objects.

The heap memory has two types of objects as follows:

  1. Live object:An object that is live in heap memory and referencing to any objectis known as live object.
  2. Dead object:An object that is no longer assigned anywhere is known as dead object.

How objects are dereferenced?

We can use the following ways to make an unused object valid for garbage collection:

  1. By making a reference null

Consider the example, a class named Employee is declared having an object named emp.

 public class Employee
{
//statements
Employee emp= new Employee();
emp= null;
} 

The second line of code makes the object emp be dereferenced.

  • Assigning an old reference to a new reference:

          Consider the example, a class named Employee is declared having two objects named emp1 and emp2.

 public class Employee
{
//statements
Employee emp1 = new Employee();
Employee emp2 = new Employee();
emp1=emp2;
} 

In the above code snippet,the last statement reassigned the object emp2 to emp1. It means thatthe abject emp1 can be removed from the memory as it does not have any new reference.

  • With the use of anonymous objects

Consider the example, a class named ‘Employee’ is declared having an object named emp.

new Employee();

There is no name to this object therefore it is valid for garbage collection.

How does the Java Garbage Collector work?

The Java garbage collector runs inside the JVM (Java Virtual Machine). Each JVM has its own version of the garbage collector. The garbage collector must satisfy the standard JVM specifications of working with the object stored in the memory heap, identifying the unreachable objects, destroying them, and compacting the memory once again.

Oracle provides a JVM named HotSpot. It has a powerful and full-fledged garbage collection option. It follows the same procedure as followed by other garbage collectors.It identifies the unreferenced objects and marks those objects for garbage collection.After that, it removes them and at last performs defragmentation on the heap memory. So that remaining objects are compacted in a contiguous memory space at the start of the memory heap.

Java Garbage Collection

The memory heap is divided into three sections:

  1. Young Generation:

The newly created objects are of the young generation. It is divided into two parts i.e. Eden and Survivor Space. In Eden, the newly generated objects are stored whilethe survivor spaces S0 and S1 have those objects that are gone through the first garbage collection cycle. The garbage collection performed in this generation is a minor garbage collection event.

  • Old Generation:

The objects that are no longer used in the program are shifted to the old generation from the young generation. These objects’ removal is called a major garbage collection event.

  • Permanent Generation:

Metadata that consists of different classes and methods is considered as a permanent generation. Removing the unused classes results in permanent garbage collection.

Advantages of Java Garbage Collection

  1. As we know programming languages like C and C++ require handling memory management manually, it becomes hectic. But Java does perform this functionality automatically with the help of JVM.  So, the programmer need not to take care of the memorymanagement.
  2. If the program contains dereferenced memory objects it may lead to memory exhaustion over a longer period of time.
  3. Garbage collection reduces certain bugs like dangling pointer bugs, memory leaks, and double-free bugs.

Disadvantages of Java Garbage Collection

  1. The garbage collector stops the execution of an entire program in order to search and collect the garbage objects. It may cause longer pauses in the case of large programs and sometimes the user may notice the same.
  2. We never know when and how long the garbage collector will run to perform its task. It might impact the performance of the software.

In this section, we have discussed about Java garbage collection and its working. In the coming section we discuss about Java gc().


Related Topics

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Java Comparable Interface

We implement comparable interface when we need a new logic for determining equality. if two objects are equal, the equals() method returns true and compareTo() method returns 0. The basic...

1 minute read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Even Odd Program in Java

Even Odd Program in Java The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4,...

5 minutes read.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Volatile keyword in Java

Multiple threads can change a variable's value by using the volatile keyword. Making classes thread-safe is another application for it. It indicates that using a method or an instance of...

3 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.

Bin Packing Problem Java

Assigning some items with known weights to bins with consistent capacities is necessary for the bin packing problem. The goal is to use the smallest possible boxes while ensuring everything is put...

6 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.