system class – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sat, 20 Aug 2022 14:54:45 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg system class – Programmerbay https://programmerbay.com 32 32 Java Garbage Collection And its Working With Program Example https://programmerbay.com/java-garbage-collection-and-its-working-with-program-example/ https://programmerbay.com/java-garbage-collection-and-its-working-with-program-example/#respond Sat, 09 Jul 2022 11:07:37 +0000 https://www.programmerbay.com/?p=4186 Introduction:

Terms:

Reachable & unreachable objects: Objects that can be accessed by a reference variable are known as reachable object. When there is no reference available to access an object, in any way,  it is called unreachable.

Garbage: Useless objects or unreachable objects or objects that can no longer be referenced.

Garbage collector: A program that takes care of memory and manages it automatically.

Garbage collection: It is a process of reclaiming already occupied memory referenced by unreachable objects.

finalization: A process of releasing resources held by the unreachable object and invoked just before destruction.

 Journey of an Object

1. We use new keyword to create an object  and its reference gets stored in a reference variable of same class type.

2. Once the object finishes all its assigned tasks, it is highly recommended to make that object eligible for gc. So, that memory can be freed and used for further activities.

3. After making it eligible for gc, it is very important to release all the resources that are held by that object. For this intent, the finalize method is invoked.

4. And lastly, gc destroys that object and release the memory occupied by that object.

What is the need of Garbage Collector in Java ?

In C++, objects that are allocated using new operator should be destroyed manually using delete operator.

So, it is the programmer’s responsibility to remove that object from the heap memory. However, if one shows carelessness to do this job, the memory would become filled with unreachable objects.

As a result, a situation would arrive, where no further allocation of an object could be made and the most common error called ‘out of memory’ would be triggered.

But unlike C++, Java follows a different approach, it provides garbage collector whose purpose is to reclaim memory occupied by objects.

Therefore, there is no need to handle this situation manually as Garbage collector keeps monitoring memory for useless objects.

Garbage collector always run in the background to fulfill the need for memory management. It can’t be anticipated when would GC actually perform the cleaning task of memory as it depends on the approach that JVM follows.

However, it is certain that if a program is running in a low memory then JVM definitely going to execute GC.

How Does Garbage Collection in Java Work?

Unlike C++, the programmer doesn’t require to remove unused objects from heap memory in Java. Java provides a garbage collector that automates this process and its implementation lives in JVM.

How java Objects are stored in memory

Java garbage collection is a mechanism of identifying reachable & unreachable objects in heap memory, and cleaning unused ones for future allocation purpose. It’s the garbage collector’s responsibility to manage and reclaim the objects which can no longer be referenced.

What is GC root?

GC roots are the special objects to which all other objects are referenced from it and considered alive.

The garbage collector starts its process from the GC root and tracks all the objects that are directly or indirectly accessible through it on the heap. If an object can’t be referenced through GC root, then GC considers that object as a valid candidate for garbage collection

Garbage Collection Stages in Java

1) First, Garbage collector traverses each and every accessible object in the memory array through GC root. Objects that are accessible, considered as alive and inaccessible objects are considered as dead.

2) The marked dead objects occupy memory in the heap, which is then reclaimed by the Garbage collector for future object allocation.

When an object doesn’t have a reference variable, then it automatically becomes eligible for garbage collection.

Methods to run GC explicitly  a brief Article on Method to run GC explicitly ]

Using system class

System class supports a static method called gc() to run the garbage collector. gc() method does not essentially run the Garbage collector, indeed, it requests JVM to execute it. Execution of gc totally depends on the approach that JVM follows.

By using runtime class

Runtime class also supports gc() method to make a call by requesting JVM to invoke gc. It is a singleton class that consists only a single object.

As a result, new instance can’t be created, instead, we use a factory method to get the reference of runtime class.

Before destroying an object, GC invokes finalize method in order to resource deallocation and perform cleaning operation.

Finalize method   a brief Article on Finalize() ]

It allows us to perform some action before destroying a particular object.

There may be a situation where an object holds system resources and it is needed to be freed before the object gets destroyed. This is said to be finalization.

This method invokes beforehand reclaiming an object.

protected void finalize() { 
// action 
}

 

]]>
https://programmerbay.com/java-garbage-collection-and-its-working-with-program-example/feed/ 0
How to Force Garbage Collection in Java With Program Example https://programmerbay.com/how-to-force-garbage-collection-in-java-with-program-example/ https://programmerbay.com/how-to-force-garbage-collection-in-java-with-program-example/#respond Sat, 09 Jul 2022 10:46:18 +0000 https://www.programmerbay.com/?p=4195 An object without having reachable references is considered to be as unreachable which is later collected by a garbage collector in Java. A Garbage collector is responsible for destroying these objects in order to free the occupied heap memory. It is automatically invoked by JVM.

Programmatically, it’s not possible to force garbage collection. However, one can only request to JVM to perform garbage collection. There are two ways to make a request to Java Virtual Machine in order to execute garbage collector explicitly or force it for Garbage Collection:

image 2020 12 27 171539
Figure : 2 ways to force garbage collection in Java

Calling Garbage Collector Using System Class

This class support rich methods that deals with standard input and output, loading files and libraries and so on. It falls under Java.lang package. It also provides a method named gc() to request JVM to make an effort to run a garbage collector.

Syntax:

System.gc();

Since it is a static method, therefore, it is invoked by using the class name.

Program:

public class ExplicitGarbageCollectorCall
{
  @Override protected void finalize () throws Throwable
  {
    System.out.println ("I am releasing resources !");
  } 
public static void main (String[]args)
  {
    ExplicitGarbageCollectorCall obj = new ExplicitGarbageCollectorCall ();	// object is created 
      obj = null;		// now object is unreachable 
      System.gc ();
  }

}

Output:

I am releasing resources!

Calling Garbage Collector By using runtime class

Runtime class is a singleton class that deals with the interaction of an application with JRE. It consists only a single instance and getRuntime method is used to get that instance of the class.

1) Get the singleton instance of Runtime class using factory method.

Runtime obj = Runtime.getRuntime();

Since getRuntime() is a static method, therefore, the class name is used to invoke it.
2) Using this object, we now call any number of instance methods that come under Runtime class.

obj.gc();

Runtime class also comes with some useful methods these are totalMemory() and freeMemory(). As name suggests, totalMemory() returns total memory space whereas freeMemory() returns free memory space.

Program:

public class ExplicitGarbageCollectorCall
{
  @Override protected void finalize () throws Throwable
  {
    System.out.println ("I am releasing resources !");
  } 
  
  public static void main (String[]args)
  {
    ExplicitGarbageCollectorCall obj = new ExplicitGarbageCollectorCall ();	// object is created 
      obj = null;		// now object is unreachable 
      System.gc ();
    Runtime rt = Runtime.getRuntime ();
      rt.gc ();
      System.out.println ("Total memory space = " + rt.totalMemory ());
      System.out.println ("Free memory space = " + rt.freeMemory ());
  }

}

Output:

I am releasing resources!
Total memory space = 64487424
Free memory space = 63527240

There is no difference between gc() method of System and Runtime class, both are committed for doing the same task which is destruction of the unreachable object. System.gc() is an easier way to invoke GC explicitly than runtime class.

 

Frequently Asked Questions

Q1. Is it possible to force garbage collection in Java ?

No, it’s not possible to force garbage collection in Java. One can only request to Java Virtual Machine to perform garbage collection. Although, it doesn’t guarantee immediate execution of the request.

]]>
https://programmerbay.com/how-to-force-garbage-collection-in-java-with-program-example/feed/ 0