The Wayback Machine - https://web.archive.org/web/20240906001352/https://www.geeksforgeeks.org/garbage-collection-java/
Open In App

Garbage Collection in Java

Last Updated : 14 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Garbage collection in Java is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory.

What is Garbage Collection?

In C/C++, a programmer is responsible for both the creation and destruction of objects. Usually, programmer neglects the destruction of useless objects. Due to this negligence, at a certain point, sufficient memory may not be available to create new objects, and the entire program will terminate abnormally, causing OutOfMemoryErrors.

But in Java, the programmer need not care for all those objects which are no longer in use. Garbage collector destroys these objects. The main objective of Garbage Collector is to free heap memory by destroying unreachable objects. The garbage collector is the best example of the Daemon thread as it is always running in the background. 

How Does Garbage Collection in Java works?

Java garbage collection is an automatic process. Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in-use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused or unreferenced object is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed. The programmer does not need to mark objects to be deleted explicitly. The garbage collection implementation lives in the JVM. 

Types of Activities in Java Garbage Collection

Two types of garbage collection activity usually happen in Java. These are:

  1. Minor or incremental Garbage Collection: It is said to have occurred when unreachable objects in the young generation heap memory are removed.
  2. Major or Full Garbage Collection: It is said to have occurred when the objects that survived the minor garbage collection are copied into the old generation or permanent generation heap memory are removed. When compared to the young generation, garbage collection happens less frequently in the old generation.

Important Concepts Related to Garbage Collection in Java

1. Unreachable objects: An object is said to be unreachable if it doesn’t contain any reference to it. Also, note that objects which are part of the island of isolation are also unreachable. 

Integer i = new Integer(4);
// the new Integer object is reachable  via the reference in 'i' 
i = null;
// the Integer object is no longer reachable. 

garbage collection

2. Eligibility for garbage collection: An object is said to be eligible for GC(garbage collection) if it is unreachable. After i = null, integer object 4 in the heap area is suitable for garbage collection in the above image.

Ways to make an object eligible for Garbage Collector

  • Even though the programmer is not responsible for destroying useless objects but it is highly recommended to make an object unreachable(thus eligible for GC) if it is no longer required.
  • There are generally four ways to make an object eligible for garbage collection.
    1. Nullifying the reference variable
    2. Re-assigning the reference variable
    3. An object created inside the method
    4. Island of Isolation

Ways for requesting JVM to run Garbage Collector

  • Once we make an object eligible for garbage collection, it may not destroy immediately by the garbage collector. Whenever JVM runs the Garbage Collector program, then only the object will be destroyed. But when JVM runs Garbage Collector, we can not expect.
  • We can also request JVM to run Garbage Collector. There are two ways to do it : 
    1. Using System.gc() method: System class contain static method gc() for requesting JVM to run Garbage Collector.
    2. Using Runtime.getRuntime().gc() method: Runtime class allows the application to interface with the JVM in which the application is running. Hence by using its gc() method, we can request JVM to run Garbage Collector.
    3. There is no guarantee that any of the above two methods will run Garbage Collector.
    4. The call System.gc() is effectively equivalent to the call : Runtime.getRuntime().gc()

Finalization

  • Just before destroying an object, Garbage Collector calls finalize() method on the object to perform cleanup activities. Once finalize() method completes, Garbage Collector destroys that object.
  • finalize() method is present in Object class with the following prototype.
protected void finalize() throws Throwable

Based on our requirement, we can override finalize() method for performing our cleanup activities like closing connection from the database. 

  1. The finalize() method is called by Garbage Collector, not JVM. However, Garbage Collector is one of the modules of JVM.
  2. Object class finalize() method has an empty implementation. Thus, it is recommended to override the finalize() method to dispose of system resources or perform other cleanups.
  3. The finalize() method is never invoked more than once for any object.
  4. If an uncaught exception is thrown by the finalize() method, the exception is ignored, and the finalization of that object terminates.

Advantages of Garbage Collection in Java

The advantages of Garbage Collection in Java are:

  • It makes java memory-efficient because the garbage collector removes the unreferenced objects from heap memory.
  • It is automatically done by the garbage collector(a part of JVM), so we don’t need extra effort.

Real-World Example

Let’s take a real-life example, where we use the concept of the garbage collector.

Question: Suppose you go for the internship at GeeksForGeeks, and you were told to write a program to count the number of employees working in the company(excluding interns). To make this program, you have to use the concept of a garbage collector. 

This is the actual task you were given at the company:

Write a program to create a class called Employee having the following data members. 

1. An ID for storing unique id allocated to every employee. 
2. Name of employee. 
3. age of an employee.

Also, provide the following methods:

  1. A parameterized constructor to initialize name and age. The ID should be initialized in this constructor.
  2. A method show() to display ID, name, and age.
  3. A method showNextId() to display the ID of the next employee.

Now any beginner, who doesn’t know Garbage Collector in Java will code like this: 

Java




// Java Program to count number
// of employees working
// in a company
 
class Employee {
   
    private int ID;
    private String name;
    private int age;
    private static int nextId = 1;
    // it is made static because it
    // is keep common among all and
    // shared by all objects
   
    public Employee(String name, int age)
    {
        this.name = name;
        this.age = age;
        this.ID = nextId++;
    }
    public void show()
    {
        System.out.println("Id=" + ID + "\nName=" + name
                           + "\nAge=" + age);
    }
    public void showNextId()
    {
        System.out.println("Next employee id will be="
                           + nextId);
    }
}
 
class UseEmployee {
    public static void main(String[] args)
    {
        Employee E = new Employee("GFG1", 56);
        Employee F = new Employee("GFG2", 45);
        Employee G = new Employee("GFG3", 25);
        E.show();
        F.show();
        G.show();
        E.showNextId();
        F.showNextId();
        G.showNextId();
 
        { // It is sub block to keep
            // all those interns.
            Employee X = new Employee("GFG4", 23);
            Employee Y = new Employee("GFG5", 21);
            X.show();
            Y.show();
            X.showNextId();
            Y.showNextId();
        }
        // After countering this brace, X and Y
        // will be removed.Therefore,
        // now it should show nextId as 4.
           
          // Output of this line
        E.showNextId();
        // should be 4 but it will give 6 as output.
    }
}


Output

Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=6

Now to get the correct output: 
Now garbage collector(gc) will see 2 objects free. Now to decrement nextId,gc(garbage collector) will call method to finalize() only when we programmers have overridden it in our class. And as mentioned previously, we have to request gc(garbage collector), and for this, we have to write the following 3 steps before closing brace of sub-block.  

  1. Set references to null(i.e X = Y = null;)
  2. Call, System.gc();
  3. Call, System.runFinalization();

Now the correct code for counting the number of employees(excluding interns)  

Java




// Correct code to count number
// of employees excluding interns.
 
class Employee {
   
    private int ID;
    private String name;
    private int age;
    private static int nextId = 1;
   
    // it is made static because it
    // is keep common among all and
    // shared by all objects
    public Employee(String name, int age)
    {
        this.name = name;
        this.age = age;
        this.ID = nextId++;
    }
    public void show()
    {
        System.out.println("Id=" + ID + "\nName=" + name
                           + "\nAge=" + age);
    }
    public void showNextId()
    {
        System.out.println("Next employee id will be="
                           + nextId);
    }
    protected void finalize()
    {
        --nextId;
        // In this case,
        // gc will call finalize()
        // for 2 times for 2 objects.
    }
}
 
public class UseEmployee {
    public static void main(String[] args)
    {
        Employee E = new Employee("GFG1", 56);
        Employee F = new Employee("GFG2", 45);
        Employee G = new Employee("GFG3", 25);
        E.show();
        F.show();
        G.show();
        E.showNextId();
        F.showNextId();
        G.showNextId();
 
        {
            // It is sub block to keep
            // all those interns.
            Employee X = new Employee("GFG4", 23);
            Employee Y = new Employee("GFG5", 21);
            X.show();
            Y.show();
            X.showNextId();
            Y.showNextId();
            X = Y = null;
            System.gc();
            System.runFinalization();
        }
        E.showNextId();
    }
}


Output

Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=4

Related Articles:  



Previous Article
Next Article

Similar Reads

How to prevent objects of a class from Garbage Collection in Java
The garbage collector in Java is automatic, i.e the user doesn't have to manually free an occupied memory which was dynamically allocated. And how does a garbage collector decide which object is to be deleted? It's simple: the object which loses it's reference, is marked for deletion from the heap memory. For example, look at the following piece of
5 min read
Output of Java programs | Set 10 (Garbage Collection)
Prerequisite - Garbage Collection in Java Difficulty level : Intermediate In Java, object destruction is taken care by the Garbage Collector module and the objects which do not have any references to them are eligible for garbage collection. Below are some important output questions on Garbage collection. Predict the output of following Java Progra
4 min read
How to make object eligible for garbage collection in Java?
An object is eligible to be garbage collected if its reference variable is lost from the program during execution.Sometimes they are also called unreachable objects. What is reference of an object? The new operator dynamically allocates memory for an object and returns a reference to it. This reference is the address in memory of the object allocat
5 min read
Does Garbage Collection Guarantee that a Program will not Run Out of Memory?
The work of Garbage collection in Java is to automate the process of deleting memory that's no longer in use. But does that mean Java programs are free from memory limit overflow? Well in this article we will discuss it in brief, but first, let's talk about the garbage collection in Java. Garbage Collection:In C/C++, a programmer is responsible for
3 min read
Mark-and-Sweep: Garbage Collection Algorithm
There are many garbage collection algorithms that run in the background, of which one of them is mark and sweep. All the objects which are created dynamically (using new in C++ and Java) are allocated memory in the heap. If we go on creating objects we might get Out Of Memory error since it is not possible to allocate heap memory to objects. So we
5 min read
Java Program to Get the Size of Collection and Verify that Collection is Empty
The size() and isEmpty() of java.util.Collection interface is used to check the size of collections and if the Collection is empty or not. isEmpty() method does not take any parameter and does not return any value. Example: Input:[99, 54, 112, 184, 2] Output:size = 5 and Collection is not empty Input:[] Output: size = 0 and Collection is emptysize(
2 min read
Difference Between Collection.stream().forEach() and Collection.forEach() in Java
Collection.forEach() and Collection.stream().forEach() are used for iterating over the collections, there is no such major difference between the two, as both of them give the same result, though there are some differences in their internal working. Collection.stream().forEach() is basically used for iteration in a group of objects by converting a
3 min read
Types of JVM Garbage Collectors in Java with implementation details
prerequisites: Garbage Collection, Mark and Sweep algorithm Garbage Collection: Garbage collection aka GC is one of the most important features of Java. Garbage collection is the mechanism used in Java to de-allocate unused memory, which is nothing but clear the space consumed by unused objects. To deallocate unused memory, Garbage collector track
5 min read
Z Garbage Collector in Java
Today, it's common for applications to respond to thousands or even millions of users concurrently. Such applications need immeasurable amounts of memory. However, managing all that memory may easily impact application performance. To overcome this issue java 11 includes a lot of improvements and changes in the GC(Garbage Collection) domain. Java 1
6 min read
Different Ways to Collect Garbage in Java HotSpot JVM
JDKs come with different JVM implementations (Oracle HotSpot, Eclipse OpenJ9, GraalVM, Jikes RVM, Codename One), and different garbage collector implementations with different tuning options (Serial, Parallel, CMS, G1, Z, Shenandoah). In this article, we will know more about the Garbage Collector, how it works, and the various types of GC available
7 min read
Iterator vs Collection in Java
Iterator and Collection, both has helped and comforted the programmers at many a times. But their usage and application has a very wide difference. 1. Iterator Declaration public interface Iterator Type Parameters: E - the type of elements returned by this iteratorIterators are used in Collection framework in Java to retrieve elements one by one. M
3 min read
Convert an Iterable to Collection in Java
Iterable and Collection have served to be of great use in Java. Iterators are used in Collection framework in Java to retrieve elements one by one and a Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single
4 min read
Finding minimum and maximum element of a Collection in Java
A Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit. These are: Finding minimum and maximum element of a Collection can be easily done using the Collections.min() and Collections.max() method. Thes
6 min read
Non-generic Vs Generic Collection in Java
We will be discussing differences later prior let us understand what is generic Collection and non-generic Collection, and most importantly dealing with the implementation part as during implementation one can only really get the real understanding of the concept, henceforth the differences between them. Generics are basically the errors appearing
5 min read
Collection addAll() method in Java with Examples
The addAll(Collection collection) of java.util.Collection interface is used to add the Collection 'collection' to this existing collection. This method returns a boolean value depicting the successfulness of the operation. If the collection was added, it returns true, else it returns false. Syntax: Collection.addAll(Collection<E> collection)
3 min read
Collection add() Method in Java with Examples
The add(E element) of java.util.Collection interface is used to add the element 'element' to this collection. This method returns a boolean value depicting the successfulness of the operation. If the element was added, it returns true, else it returns false. Syntax: Collection.add(E element) Parameters: This method accepts a mandatory parameter ele
4 min read
Collection contains() method in Java with Examples
The contains(Object element) of java.util.Collection interface is used to check whether the element 'element' exists in this collection. This method returns a boolean value depicting the presence of the element. If the element is present, it returns true, else it returns false. Syntax: Collection.contains(Object element) Parameters: This method acc
3 min read
Stack addAll(int, Collection) method in Java with Example
The addAll(int, Collection) method of Stack Class is used to append all of the elements from the collection passed as a parameter to this function at a specific index or position of a Stack. Syntax: boolean addAll(int index, Collection C) Parameters: This function accepts two parameters as shown in the above syntax and are described below. index: T
2 min read
Stack addAll(Collection) method in Java with Example
The addAll(Collection) method of Stack Class is used to append all of the elements from the collection passed as a parameter to this function to the end of a Stack keeping in mind the order of return by the collection's iterator. Syntax: boolean addAll(Collection C) Parameters: The method accepts a mandatory parameter C which is a collection of Arr
2 min read
How to Add All Items From a Collection to an ArrayList in Java?
Given a Collection with some values, the task is to add all the items of this Collection to an ArrayList in Java. Illustrations: Input: Collection = [1, 2, 3] Output: ArrayList = [1, 2, 3]Input: Collection = [GFG, Geek, GeeksForGeeks] Output: ArrayList = [GFG, Geek, GeeksForGeeks] Approach: Get the Collection whose items are to be added into the Ar
2 min read
How to add selected items from a collection to an ArrayList in Java?
Given a Collection with some values, the task is to add selected the items of this Collection to an ArrayList in Java. Examples: Input: Collection = [1, 2, 3], condition = (item != 2) Output: ArrayList = [1, 3] Input: Collection = [GFG, Geek, GeeksForGeeks], condition = (item != GFG) Output: ArrayList = [Geek, GeeksForGeeks] Approach: Get the Colle
2 min read
Collecting a Stream to an Immutable Collection in Java
Streams and Collectors were introduced in Java 8 introduced the concept of Streams. A Stream is a sequence, a sequence of objects. We generate Streams from input sources like Arrays, Lists, etc., and support aggregation operations like filter, map, limit, reduce, etc. We use Streams to pipeline data and ultimately collect it into some form of a Col
6 min read
Collection Interface in Java with Examples
The Collection interface is a member of the Java Collections Framework. It is a part of java.util package. It is one of the root interfaces of the Collection Hierarchy. The Collection interface is not directly implemented by any class. However, it is implemented indirectly via its subtypes or subinterfaces like List, Queue, and Set. For Example, th
8 min read
How to Make a Collection Read-Only in Java?
The Collections class is used as a data structure to manage the data. We can add, remove, fetch, and update the data in the List, Set, or Map Object. Collections class has default methods for these operations. We can use those methods easily. By default, when we create an object of the Collections class, it will be Both Readable and Writable. Read-
4 min read
Why We Need Collection Framework in Java?
A framework is a set of classes and interfaces which provide a ready-made architecture. In order to implement a new feature or a class, there is no need to define a framework. However, an optimal object-oriented design always includes a framework with a collection of classes such that all the classes perform the same kind of task. Before Collection
3 min read
Java Collection retainAll() Method
In Java, the retainAll() method of Java Collection retains or keeps only those elements present inside the collection which is given as an argument to the function. Syntax for retainAll() method: boolean retainAll(Collection<?> c);Parameters: c is the collection containing elements retained or kept by the calling collection. Return Type:It re
3 min read
Java Collection removeAll() Method with Examples
The removeAll() method of Java Collection removes those elements from the collection that are contained in the collection which is given as an argument to function. Syntaxboolean removeAll(Collection<?> c);Parameters:c is the collection containing elements that are removed from the calling collection.Return Type: It returns a boolean value. I
2 min read
Java Collection containsAll() Method with Examples
The Collection interface in Java is the fundamental part of the Collection hierarchy. It is found in the java.util package and offers a wide range of built-in classes and methods. One such useful method is containsAll(). Java containsAll() methodThe purpose of this containsAll() is to check whether a collection contains all the elements present in
3 min read
Java Collection removeIf() Method
The removeIf() method of Java Collection removes all the elements of the calling collection that satisfy the given predicate which is passed as a parameter to the function. If the predicate is true, then it removes the item from the calling collection otherwise it keeps the item in the collection. Syntax for removeIf()boolean removeIf(Predicate<
3 min read
Java Collection spliterator() with Examples
The spliterator() in Java Collection creates a spliterator over the elements in the collection. In simple words, it's an iterator that allows you to traverse the elements individually but is specially designed to work in parallel processing scenarios. The difference between Iterator and Spliterator is iterator does not support parallel programming
2 min read
Article Tags :
Practice Tags :