Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How Garbage Collection works in Java

In this article we will describe how garbage collection works in java and its advantages/disadvantages.

Introduction

As the name suggests, Garbage Collection refers to removing of objects which are no longer in use. It is a well known fact that irrespective of their scope objects, Java stores objects in heap. Thus, if we keep on creating objects without clearing the heap, our computers might run out of heap space and we get ‘Out of Memory’ error. Garbage Collection in Java is a mechanism which is controlled and executed by the Java Virtual Machine (JVM) to release the heap space occupied by the objects which are no more in use. In contrast to C++, garbage collection in java relives the developer from the Memory Management related activities. The JVM executes this process with the help of a demon thread called the ‘Garbage Collector’. The garbage collector thread first invokes the finalize method of the object. This performs the cleanup activity on the said object. As a developer we cannot force the JVM to run the garbage collector thread. Though there are methods e.g Runtime.gc () or System.gc(), but none of these assures the execution of garbage collector thread. These methods are used to send garbage collection requests to the JVM. It is up to the Java Virtual machine when it will initiate the garbage collection process.

Heap Generation for Garbage Collection

For the sake of Garbage Collection in Java, Heap memory is divided into three parts :

  • Young Generation
  • Tenured or Old Generation
  • Permanent Generation

Young Generation is further divided into three parts known namely Eden space, Survivor 1 and Survivor 2 space. A live object resides in Eden space and after a Minor Garbage collection if the object is still live it is moved into survivor 1 and subsequently to survivor 2. Finally after the Major Garbage collection the object is moved to Old or tenured generation.

Full GC and Concurrent GC

In java, Concurrent garbage collector uses a single GC thread that runs in tandem with the application threads. This has a goal to complete the collection of the tenured generation before it becomes full. If the concurrent garbage collector is still running and the tenured generation heap is full, the application is halted and the collection is completed with all the application threads stopped. This garbage collection is referred to as full Garbage Collection

Eligibility

An object becomes eligible to be garbage collected if its references are nullified. In other words an object is picked by the garbage collector if it cannot be reached by any live thread or it does not have any static reference. If two objects have cyclic dependency and none of them are referenced by any other live threads then both of these objects are eligible for garbage collection. In Java, an object becomes eligible for garbage collection under the following circumstances:

  • When the reference to the said object is nullified or set to null explicitly.
  • When the control moves out of the block which creates the object.
  • When an object holding the reference of another object is set to null, then both the objects - child and parent are eligible for garbage collection.

The Algorithm

The garbage collection algorithm performs the following two basic tasks:

  • It first checks whether the objects is eligible or not to be garbage collected.
  • Once the object is identified, the garbage collector reclaims the heap space used by the object and makes the space available back to the program.

Detection of the eligible object is done by defining a set of roots and tracing the reachability from the roots. An object is said to be reachable if there exists a path of reference from the roots using which the executing program can access the object. These roots once defined are accessible to the executing program. An object which is reachable from any of these roots is considered to be "live." Objects that are not reachable by the defined roots are considered to be garbage, as they cannot put any impact on the execution of the program further. In addition to this, an object which is referred by a live object is also considered as reachable. These reachable objects are accessible by the executing program; hence, these objects should remain on the heap as long as they are required. An object which is not reachable can be garbage collected since there is no way a program can access it.

So the available System.gc() method can be used to request garbage collection. And the System.runFinalization() method is used to run finalizers for all the eligible objects for GC.

Listing 1: The sample describes the syntax for calling garbage collection and finalizer

static void gc() // Requests GC to run
static void runFinalization() // Requests finalizers to run

Listing 2: Sample program performs garbage collection. The free memory before and after garbage collection is returned and displayed.

import java.util.*;
 
class GarbageCollectionDemo
{
   public static void main(String s[]) throws Exception
   {
      // Get runtime environment
Runtime rt =  Runtime.getRuntime(); 
System.out.println("Free memory before Garbage Collection = "+rt.freeMemory());
      
      // Apply garbage collection
     	 rt.gc();
System.out.println("Free memory after Garbage Collection = "+rt.freeMemory());
   }
} 

The following diagram describes the garbage collection model in java.

Garbage Collection Model in Java

Figure 1: Garbage Collection Model in Java

Types of Garbage Collector

Since J2SE 5.0, we have following types of Garbage collectors. Programmers can normally choose any of these to reclaim the unused memory using the JVM Parameters. These are mentioned as under:

The table below describes different types of garbage collectors

Garbage Collector Type JVM Option Parameter Other Options
Serial Collector XX:+UseSerialGC
Throughput Collector XX:+UseParallelGC Young Generation GC are done in parallel threads Tenured Generation GC are done in Serial threads
Parallel Old Generation Collector XX:+UseParallelOldGC Some Old Generation GC can be done in parallel threads, which enhances the performance
Concurrent Low Pause Collector Xincgc or XX:+UseConcMarkSweepGC Used to collect the tenured generation Cocnurrently.
Incremental Low Pause Collector XX:+UseTrainGC Not supported after JSE 1.4.2

Advantages of Garbage Collection

Garbage collection mechanism takes off the burden of a developer to manually release the memory. Allocating the task of memory management to JVM has lots of advantages:

  • The developer can devote more time and energy on dealing with complicated business scenario. While in case of non-garbage-collected languages developers may spend, hours, days or even weeks to find out a memory leak.
  • Memory management by the JVM ensures the integrity of the program. Since releasing of memory is completely handled by the JVM, there is a very less chance that a developer can crash the JVM by releasing the memory which still has some reference.

Disadvantages of Garbage Collection

  • Garbage Collection mechanism consumes extra resources in deciding what memory should be freed. The JVM has to keep a track of all objects and keep on checking which object is referenced and which is not. This activity leads to decreased or uneven performance as a certain section of the CPU is always busy in performing this task.

Conclusion

Garbage Collection is the mechanism of reclaiming the heap memory by flushing out the objects which are not referenced by any threads.

For the sake of garbage collection, java heap is divided into three generations :

  • Young generation
  • Tenured or old generation
  • Permanent area.

Newly created and live objects reside within young generation and subsequently moved to the old generation as their references are weakened.

Garbage Collection happens in two steps:

  • Minor garbage collection - This is used to move object from Eden space to Survivor 1 and Survivor 2 space
  • Major garbage collection - This is used to move object from young to tenured generation.

Garbage Collection relieves the developer from taking care of memory management.

Garbage Collection has an impact on the performance of the program.

There are following types of Garbage Collector :

  • Serial Collector
  • Throughput Collector
  • Parallel Old Generation Collector
  • Concurrent Low Pause Collector
  • Incremental Low Pause Collector

There is no manual way of doing garbage collection in Java.

Also read



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login