garbage collection – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Thu, 14 Jul 2022 15:30:50 +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 garbage collection – 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 make an object eligible for Garbage collection in Java? https://programmerbay.com/how-to-make-an-object-eligible-for-garbage-collection-in-java/ https://programmerbay.com/how-to-make-an-object-eligible-for-garbage-collection-in-java/#respond Sat, 04 Jun 2022 15:34:40 +0000 https://programmerbay.com/?p=7894 A garbage collector is a program that ensures automatic memory management and runs periodically to recycle unreachable objects. It is responsible for reclaiming already occupied memory referenced by unreachable objects, the process is called garbage collection.

When an object doesn’t have any references, it becomes automatically eligible for garbage collection.

A reference object gets memory at runtime which occupies space in heap area. If Java finds it as unreachable or unused, then it is considered as an dead which becomes eligible for garbage collection.

However, there are four ways to make an object qualified for the garbage collection.

[Also read: How to Force Garbage Collection in Java With Program Example]

4 ways to make an object eligible for garbage collection

  • Nullifying the reference variable

A reference variable always points to an address of the actual copy of an object. If this particular address is replaced by null value, the object can no longer be accessed through that variable.

Therefore, assigning null value would break the link between the object and reference variable, making it eligible for garbage collection.

How variable references to object

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

}
  • Reassign the reference variable

In this, if an object is not required and at the same time there is need to work on another object, we simply shift reference of the variable from useless object to a new object.

As a result, the old one becomes eligible for garbage collection.

heap and stack storage of object

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


}
  • Object created in a method

When an object is created in a local method, it acts like a local variable. And when that particular method finishes its execution, it goes out of scope, the reference variable pointing to the object automatically gets destroyed, but not the actual object.

However, if a method returns an object and  its reference is assigned to a variable, then the object would no longer be eligible for garbage collection.

As a result, the reference to the object breaks and the object becomes unreachable.

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

}
  • Island of isolation

When there is a group of objects that are internally referencing to each other and if no root object reference to them, then these group of objects collectively eligible for garbage collection.

island of islotion 2

island of isolation 1

Program:

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

}

 

]]>
https://programmerbay.com/how-to-make-an-object-eligible-for-garbage-collection-in-java/feed/ 0