×

Java gc()

Garbage collection

Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced and destroyed to free up memory space. The task is performed by a garbage collector that resides inside the JVM (Java Virtual Machine). When dereferenced objects are shifted from the young generation to the old generation, the garbage collector is executed.

The JVM can perform garbage collection operation during the execution program. But we don’t know when it’s going to be executed. Hence, we can make JVM run a garbage collector at least once throughout the execution of the program by using System.gc() method.

How to mark an object for garbage collection?

There are different ways to make an unused object eligible for garbage collection.

  1. By making a reference null
  2. Assigning an old reference to new reference
  3. With the use of anonymous object

All these methods are explained in the previous article about Java garbage collector.

Ways to implementgc() method

  1. Using System.gc() Method

System.gc() is a method available in java.lang package. It can be invoked by using simple syntax.

Syntax:

System.gc()

DemoGC.java

 public class DemoGC
{
    public static void main(String a[])
    {     
        DemoGC d = new DemoGC(); 
        /* marking an object d for garbage collection */
        d=null; 
        /* call to gc() method */
System.gc(); 
    }
    @Override
    public void finalize()
    {
        System.out.println("Garbage collector method executed for object: "+this);
    }
} 

Output:

 Garbage collector method executed for object: DemoGC@7978f9b4
Garbage collector method executed for object: DemoGC@77bf18eb 

In the above code, a class DemoGCis declared. An object d of the class DemoGC is marked for garbage collection by marking d as null. After that System.gc() method is called.

The output contains the object id that is destroyed by the gc() method.

  • Using Runtime.getRuntime.gc() method

The Runtime class permits the application to make an interface with the JVM. And it executesgc() method to perform garbage collection.

GcExample.java

 public class GcExample
{
    public static void main(String a[])
    {
GcExample d1=new GcExample();
GcExample d2=new GcExample();
        /* marking object d1 for garbage collection */
        d1=d2;
        /* call to gc() method */
     Runtime.getRuntime().gc();
    }
    @Override
    public void finalize()
    {
        System.out.println("Garbage collector method executed for object: "+this);
    }
} 

Output:

Garbage collector method executed for object: DemoGC@7978f9b4

In the above code, a class DemoGCis declared. Two objects d1 and d2 are declared. An object d1of the class DemoGC is marked for garbage collection by assigning the old reference to new reference. After that System.gc() method is called.

The output shows the object id that is destroyed by the gc() method.

Advantages of gc() method

  1. When an application or server is started many objects are getting invoked. After that those object needs to be finalized. At this time we can call System.gc() method to clear up the memory space.
  2. System.gc() method can be used while debugging the program. To check whether memory leak is not happening in the system.

Disadvantages of gc() method

  1. The gc() method may execute for unlimited time. Itimpacts the further execution of the program. Ultimately affecting the performance of program.

Example of using gc() method

The below code counts the number of staff working in the hotel (excluding new staff).The concept of a garbage collector is used for this program.
Hotel.java

 /* code to count total number of Hotel staff excluding new employees. */
class Hotel
{
     private int empid;
     private String empname;
     private int empage;
     private static int nextId=1;
     /*it is made static because it is shared by all objects*/
     public Hotel(String empname,int empage)
     {
              this.empname = empname;
              this.empage = empage;
              this.empid = nextId++;
     }
     public void show()
     {
              System.out.println("Staff ID="+empid+"\nName="+empname+"\nAge="+empage);
     }
     public void showNextId()
     {
              System.out.println("Next staff id will be="+nextId);
     }
     protected void finalize()
     {
              --nextId;
              /*In this case, gc will call finalize() for 2 times for 2 objects.*/
     }
}// End of Hotel
public class HotelMaster
{
    //main()
     public static void main(String a[])
     {
              Hotel h1=new Hotel("Staff1",42);
              Hotel h2=new Hotel("Staff2",36);
              Hotel h3=new Hotel("Staff3",30);
              h1.show();
              h2.show();
              h3.show();
              h1.showNextId();
              h2.showNextId();
              h3.showNextId();
              {
                        /* this contains the new staff entries and again marking them for garbage collection. */
                        Hotel e1=new Hotel("Staff4",22);    
                        Hotel e2=new Hotel("Staff5",24);
                        e1.show();
                        e2.show();
                        e1.showNextId();
                        e2.showNextId();
                        e1 = e2 = null;
                        System.gc();
                        System.runFinalization();
              }
     h1.showNextId();
     }
}//End of HotelMaster 

Output:

 Staff ID=1
Name=Staff1
Age=42
Staff ID=2
Name=Staff2
Age=36
Staff ID=3
Name=Staff3
Age=30
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Staff ID=4
Name=Staff4
Age=22
Staff ID=5
Name=Staff5
Age=24
Next employee id will be=6
Next employee id will be=6
Next employee id will be=4 

In this way, this article helps to learn more about System.gc() method used for garbage collection in Java.


Related Topics

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Java Extends keyword

Extends Extends is a keyword which is completely depended on the concept of the inheritance of the java programming language.To understand about of the keyword, we need to learn the concept...

3 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.