×

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

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

Hello Program in Java

Hello Program in Java The Hello program in Java displays the word Hello on the console. It is the basic program in Java. In this section, we will learn different ways...

3 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.