Garbage Collection in Java

Garbage Collection in Java with Examples

In this article, I am going to discuss Garbage Collection in Java with Examples. Please read our previous where we discussed Association Composition and Aggregation in Java in detail. At the end of this article, you will understand what is Garbage Collection and How Garbage Collection works in Java with Examples?

Garbage collection (GC), as its name implies, is a means of freeing space occupied by waste materials, or garbage, and avoid memory leaks. Through performing the GC mechanism, available memory can be effectively used.

What is Garbage Collection in Java?

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 object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed. In reality, Garbage Collection tracks each and every object available in the JVM heap space and removes unused ones.

In a programming language like C, allocating and deallocating memory is a manual process. In Java, the process of deallocating memory is handled automatically by the garbage collector.

How does Garbage Collection work in Java?

Java garbage collection is an automatic process. The programmer does not need to explicitly mark objects to be deleted. However, we can request the JVM for garbage collection of an object but ultimately it depends on the JVM to call garbage collector.

Let’s start with the heap, which is the area of memory used for dynamic allocation. In most configurations, the operating system allocates the heap in advance to be managed by the JVM while the program is running. This has a couple of important ramifications:

Object creation is faster because global synchronization with the operating system is not needed for every single object. An allocation simply claims some portion of a memory array and moves the offset pointer forward. The next allocation starts at this offset and claims the next portion of the array.

When an object is no longer used, the garbage collector reclaims the underlying memory and reuses it for future object allocation. This means there is no explicit deletion and no memory is given back to the operating system.

In simple words, GC works in two simple steps known as Mark and Sweep:

  1. Mark – it is where the garbage collector identifies which pieces of memory are in use and which are not.
  2. Sweep – this step removes objects identified during the “mark” phase.

How Garbage Collection works in Java?

Can the Garbage Collection be forced explicitly?

No, the Garbage Collection can not be forced explicitly. We may request JVM for garbage collection by calling System.gc() method. But This does not guarantee that JVM will perform the garbage collection.

When does JVM perform Garbage Collection?

Even though the programmer is not responsible to destroy useless objects but it is highly recommended to make an object unreachable (thus eligible for GC) if it is no longer required. Following are the different ways to make an object eligible for Garbage Collection:

Set null to object reference which makes it able for garbage collection.
Employee obj = new Employee();
obj = null;

By anonymous object.
new Employee();

By assigning a reference to another.
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2; //now the first object referred by e1 is available for garbage collection

Types of Garbage Collector in Java

The JVM actually provides four different garbage collectors, all of them generational. The choice of which garbage collector to use lies with us and there can be dramatic differences in the throughput and application pauses. So, the four types of garbage collectors are:

The Serial GC :

The serial collector is the default for client style machines in Java SE 5 and 6. With the serial collector, both minor and major garbage collections are done serially (using a single virtual CPU). In addition, it uses a mark-compact collection method. This method moves older memory to the beginning of the heap so that new memory allocations are made into a single continuous chunk of memory at the end of the heap. This compacting of memory makes it faster to allocate new chunks of memory to the heap.

The Parallel GC :

The parallel garbage collector uses multiple threads to perform the young generation garbage collection. By default on a host with N CPUs, the parallel garbage collector uses N garbage collector threads in the collection. Multiple threads are used for minor garbage collection. A single thread is used for major garbage collection and Old Generation compaction. Alternatively, the Parallel Old variant uses multiple threads for major garbage collection and Old Generation compaction.

The Concurrent Mask Sweep (CMS) Collector :

The Concurrent Mark Sweep (CMS) collector (also referred to as the concurrent low pause collector) collects the tenured generation. It attempts to minimize the pauses due to garbage collection by doing most of the garbage collection work concurrently with the application threads. Normally the concurrent low pause collector does not copy or compact the live objects. A garbage collection is done without moving the live objects. If fragmentation becomes a problem, allocate a larger heap.

The G1 Garbage Collector :

The Garbage First or G1 garbage collector is available in Java 7 and is designed to be the long term replacement for the CMS collector. The G1 collector is a parallel, concurrent, and incrementally compacting low-pause garbage collector that has quite a different layout from the other garbage collectors described previously. It works quite differently under the hood compared to the older garbage collectors.

finalize() Method

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. The finalize() method is invoked each time before the object is garbage collected. The finalize() method is called by garbage collection thread before collecting objects. Its the last chance for any object to perform cleanup utility.

Syntax:
Protected void finalize()
{
     //finalize code
}

Note:

  • It is defined in java.lang.Object class, therefore it is available to all the classes.
  • The finalize() method is never invoked more than once for any given object.
  • The Garbage collector of JVM collects only those objects that are created by a new keyword. So if you have created an object without new, you can use the finalize method to perform cleanup processing (destroying remaining objects).
  • It is declared as protected inside Object class.
  • If an uncaught exception is thrown by the finalize() method, the exception is ignored and finalization of that object terminates.
Request for Garbage Collection

Once we made objects eligible for garbage collection, but we can not expect when JVM runs Garbage Collector. It may not destroy immediately by the garbage collector. Whenever JVM runs the Garbage Collector program, then only the object will be destroyed.

So, we can request JVM by following two ways:

  1. Using System.gc() method : System class contain static method gc() for requesting JVM to run Garbage Collector.
  2. Using Runtime.getRuntime().gc() methodRuntime 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 the Garbage Collector.
Sample Program for Java Collection in Java
package Demo;

public class GarbageCollectionDemo {
 public void finalize(){
  System.out.println("Garbage Collection performed by JVM");
 }  
  public static void main(String args[]){  
   GarbageCollectionDemo s1=new GarbageCollectionDemo();  
   GarbageCollectionDemo s2=new GarbageCollectionDemo();  
   s1=null;  
   s2=null;  
   System.gc();  
  } 
}

Output:

Advantages of Java Garbage Collection
  • It is done automatically by JVM.
  • It makes java memory-efficient because garbage collector removes the unreferenced objects from heap memory.
  • The programmer doesn’t need to worry about manual memory allocation/deallocation handling because unused memory space is automatically handled by GC.
Disadvantages of Garbage Collection in Java
  • Programmers have no control over the scheduling of CPU time dedicated to freeing objects that are no longer needed
  • There is no guarantee that anyone of GC methods will definitely run Garbage Collector.
  • Automatized memory management will not be as efficient as the proper manual memory allocation/deallocation.

In the next article, I am going to discuss the Final Keyword in Java with examples. Here, in this article, I try to explain the Garbage Collection in Java with examples. I hope you enjoy this How Garbage Collection works in Java with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this How Garbage Collection works in Java with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *