×

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 Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

How to Split the String in Java with Delimiter

In Java, splitting strings is a significant and typically used activity while coding. Java gives different ways of dividing the String. The most widely recognized way is to use the...

3 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

Shallow copy in Java

Java's most important task is making a copy or clone of an object. In this part, we'll talk about shallow copies in Java and how to make them of Java...

4 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

10 minutes read.

Java Wrapper Class

Wrapper class in Java encapsulates a primitive type within an object. In other words, it is a unique mechanism of Java to convert primitive type in to object and object into primitive type....

3 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

List of Constants in Java

In this tutorial, we are going to deal with constants available in Java.Every programming language has its constants. Similarly, Javaalso has got constants of its own. In this tutorial, we will...

6 minutes read.

Java Calculate Average of List

The list is a linear data structure used in Java to store ordered data collections. Additionally, it accepts duplicate values while maintaining insertion order. It is sometimes necessary to find...

3 minutes read.