---
# System prepended metadata

title: Garbage Collection in Java - Scaler Topics

---

---
title: Garbage Collection in Java - Scaler Topics
description: Learn about Garbage Collection in Java by Scaler Topics. The garbage collector program does the cleaning job, removing unwanted variables from memory.
author: "Srijan Kumar Samanta"
category: "Java"
---
:::section{.abstract}

Garbage collection is a crucial aspect of automatic memory management in programming languages like Java. Garbage collection in java is about removing unused variables from the memory so that there is sufficient space for the new variables. Garbage collection works automatically in Java, making memory management more efficient. Garbage collection operates within the heap, the area of memory allocated to the Java Virtual Machine (JVM) for storing objects.
:::


:::section{.main}
## What is Garbage Collection?

Just like in our daily life we clean out homes, collect garbage and dump it in dustbins, the computer programs also require the cleaning of unused and garbage items. What happens if we don’t collect the garbage from our homes? It will create a mess and it will be difficult to find clean space to work or stay. In a similar context, if we don’t clean our running program, it will eat up the memory and make it difficult for us to maintain a healthy system. In computer languages, garbage is a variable that is no longer used. In this article, we will refer to the Garbage Collector as GC, a common term used in Java.

![garbage collection in java](https://scaler.com/topics/images/garbage-collection-in-java-768x768.webp)


Many variables are created and kept in the memory when a program runs. With time, this count will keep increasing, and a time will come when the program will run out of memory and subsequently crash. In java, we define this problem as **OutOfMemoryError**. We can also call this scenario a Memory Leak. We don’t want this, right? One solution is to have a massive RAM. But this is not a feasible solution. Let’s see how Java copes with this issue.

A garbage collector is a program that removes unwanted variables from memory. In C and C++, we do it manually by writing a method to handle this. But in Java, it is much easier. Java itself does the job for us in the background. A background thread running in Java keeps track of the objects that are eligible for removal from memory. We don’t even have to think of Garbage Collection in Java. Though Java does it, we need to have some control over it. Along with automatic garbage collection in Java, Java provides us with some features to configure when the GC should run or which type of GC to use.

:::
:::section{.main}
## How Does Garbage Collection Work in Java?

Java uses an automatic garbage collection system. The programmer does not need to explicitly indicate items for deletion.

The JVM houses the garbage collection implementation. Garbage collection can be implemented in different ways by each JVM. To deal with the objects in the heap memory, marking or identifying the unreachable objects and compaction them is required; it must adhere to the standard JVM specification.

GC runs in two phases to do the cleaning job. We call it Mark and Sweep. In the Mark step, GC “paints” the objects which are active, leaving the dead objects unmarked. The next Sweep step is performed where the GC looks for unpainted objects and collects them for removal from memory.

:::
:::section{.main}
## Types of Events in Java Garbage Collection

In Java, garbage collection events encompass two primary types:

1. **Minor or Incremental Garbage Collection:** This event occurs when the Java Virtual Machine (JVM) identifies and removes unreachable objects in the young generation heap memory. It focuses on reclaiming memory occupied by short-lived objects, thus ensuring efficient memory management.

2. **Major or Full Garbage Collection:** This event occurs when surviving objects from the minor garbage collection phase are transferred to the old or permanent generation heap memory. Unlike minor collections, the major collection addresses long-lived objects, making them less frequent but crucial for maintaining overall memory health.
:::

:::section{.main}
## Advantages of Garbage Collection in Java

The primary function of the Garbage collector is to automatically reclaim memory occupied by objects no longer in use or referenced by the program. This process helps prevent memory leaks and optimizes the utilization of memory resources. Some of the significant advantages of garbage collection in java are mentioned below:

* Garbage collection in Java provides a crucial advantage by efficiently managing memory. 
* Automatically removing unreferenced objects from the heap memory streamlines memory usage without requiring manual intervention. 
* This automation, which the garbage collector handles as part of the JVM, simplifies memory management tasks, sparing developers from the need for additional efforts.

:::

:::section{.main}
## How Can an Object Be Unreferenced?

There are various methods for allowing Java's garbage collector to reclaim memory:

1. **Nullifying a reference**

Here, we first create an object for a class and then assign null to it so that it become eligible for garbage collection.
```java
Person e = new Person();
e = null;
```


2. **Assigning a reference to another**

In this the reference of the original object is changed to another object and hence all the objects which are referenced by first object become eligible for garbage collection.
```java
Person e1 = new Person();
Person e2 = new Person();
e1 = e2; // Now the original object referenced by e1 can be garbage collected
```

3. **Using an anonymous object**
```java
new Person();
```

These techniques facilitate the automatic memory management provided by Java's garbage collector, ensuring efficient memory usage in Java programs.


:::

:::section{.main}
## finalize() Method


The `finalize()` method in Java serves as a mechanism for performing cleanup operations on an object before it gets garbage collected. The finalize() method, present in the Object class, is called just before an object is garbage collected. It allows for cleanup operations to be executed, aiding in resource management. Its signature in the Object class is:

```java
protected void finalize(){}
```
This method provides an opportunity to release any resources or perform any necessary cleanup tasks before the object is removed from memory. Due to its limitations and potential performance issues, the finalize() method has been deprecated in Java 9.
:::

:::section{.main}
## gc() Method
The `gc()` method in Java is a part of the System class and is used to suggest to the JVM (Java Virtual Machine) that it should run the garbage collector. The `gc()` method triggers the garbage collector to execute cleanup operations. However, it's important to note that calling `gc()` does not guarantee immediate garbage collection.  This method is available in both the System and Runtime classes. 

The Syntax for gc() method is declared as:

```java
public static void gc() {}
```
:::

:::section{.main}
## Real-World Example of Java Garbage Collection 

```java
public class Main {
    public void finalize() {
        System.out.println("Object is garbage collected");
    }

    public static void main(String[] args) {
        Main obj1 = new Main();
        Main obj2 = new Main();

        obj1 = null;
        obj2 = null;

        System.gc(); // Request garbage collection
    }
}
```
**Output:** 

```
Object is garbage collected
Object is garbage collected
```

**Explanation:** In this example, we have a class Main with a finalize() method that prints a message when garbage is collected from an object of this class. Inside the main method, we create two objects (obj1 and obj2) of the Main class, set them to null to make them eligible for garbage collection, and then explicitly call System.gc() to request garbage collection. 

Note that the Java process's actual garbage collection is performed by the Java Virtual Machine (JVM), and the timing of when it runs is not guaranteed.

:::





:::section{.summary}
## Conclusion
- In this article, we have seen the need for a Garbage Collector in Java.
-  We also learned how Java runs and how to ask it to run whenever needed explicitly.
It is worth noting that calling GC explicitly in code is unsuitable for application performance. Hence, we should avoid using it. 
-  Since the finalize() method is deprecated, we should use the Closeable interface wherever possible.
-  Garbage collection helps mitigate the risk of memory leaks by automatically identifying and reclaiming memory associated with unreachable objects, preventing memory exhaustion over time.

:::