Java Garbage Collection

This tutorial covers all the concepts about java garbage collection, what is garbage collection, its application, its advantages, how GC (garbage collection) works with JVM?. How to scrutinize the garbage collection process and finally the methods to do so.

Java Garbage Collection

Garbage is the heap of unreferenced objects which occupy memory space without any need. In java destruction of object from memory is done without human intervention by JVM.

What is Garbage Collection in Java?

When there is no reference to an object, then that object is assumed to be no longer desired and the engaged memory is reclaimed to be released. This practice is called as garbage collection.

In languages like C++, the accountability of object creation and destruction is shouldered onto programmer. But in java it is not so, object is created by developer himself but the work off destruction is allotted to garbage collector.

Advantages of Garbage Collector

It makes the developers life simple as the most difficult task of maintaining the memory is taken care by the JVM.

As the programmer is not involved in the management of memory, it ensures the security and integrity of the application.

The process of garbage collection is fully automatic.

Condition for Garbage Collection

An object become suitable for garbage collection if it is not accessible from any live threads or by any other references.

There are some conditions for garbage collection which is described below:-

If all references of object is set to null explicitly.

If an object is local so the reference goes out of scope once control exit that block.

An object will be eligible for garbage collection if it has lived weak references via weakhashmap.

Child object automatically becomes suitable for GC if parent is set to null.

Theory About Functioning of Garbage Collection

Prior to going through the idea and functioning of garbage collection its crucial to know how the memory is owed to objects? And what are the parts or generations of memory?

The stack of memory is broken down into smaller parts or generations. They are as given below:

Young Generation is the space where memory is assigned to all the new objects, and there after when young generation is entirely engaged it leads to the minor garbage collection. And living object after a certain specified time gets moved on to old generation.

Old Generation is used to stock up long existing objects. And when they meet threshold age they get shifted to permanent generation. When it is cleaned leads to major garbage collection.

Garbage Collection Process in Java

1. Whenever a newer object is formed it gets its memory assigned to eden space.

2. Upon filling of eden space, it is accompanied with a minor garbage collection.

3. In the 3rd step, referenced objects are shifted to the first survivor space, the unreferenced objects are vanished and eden space is cleaned.

4. Same thing happens over the next period of time, unreferenced objects are cleared and referenced objects are transferred to survivor space (s1). In addition to that both eden space and survivor space’s are cleared after moving referenced objects of survivor space s0 to s1.

5. The survivor space switches at next level of minor GC. Eden spaces are cleared after the movement of referenced objects in s1 and eden space to s0.

6. Now when objects arrive at a minimum threshold age they are popped up to the old generation.

7. With the continuation of minor garbage collection the objects are continuously popped up to old generation.

8. Ultimately a major garbage collection is performed, which cleans up and compacts that space of old generation.

Unreferencing of Objects

Unreferencing can be done by following ways.

1. By Setting a Reference to null

In this method we nullify the reference to an object and once there is no reachable references the object is no longer have importance and becomes eligible for garbage collection.

Have a glance at following code.

1

2

3

4

5

6

7

8

9

publicclassReferenceGarbageDemo{

publicstaticvoidmain(String[]args){

StringBuffer greet=newStringBuffer("hello");

System.out.println(greet);

greet=null;

}

}

2. By Assignment of a Reference to new Object

In this method an object is made eligible for GC by setting the reference variable which presently refers to it to a new object.

Have a glance at the code.

1

2

3

4

5

6

7

8

publicclassReferenceGarbageDemo{

publicstaticvoidmain(String[]args){

StringBuffer greet=newStringBuffer("hello”");

StringBuffer greet_nu=newStringBuffer("good bye");

greet=greet_nu;

}

}

3. By Isolating Reference

In this method instead of removing reference, just isolate them. Think of a case where a reference to an object is also engaged to refer to a different reference to the same object.

Have a look at below code.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

publicclassDemo{

Demo name;

publicstaticvoidmain(String[]args)

{

Demo o1=newDemo();

Demo o2=newDemo();

o1.name=o2;

o2.name=o1;

o1=null;

o2=null;

// both become eligible for garbage collection

}

}

In the above example o1 refers to o2 and o2 refers to o1 but none of them is referenced by any other object, as a result both becomes entitled for garbage collection.

On the other hand we must keep in mind that the garbage collection is not at all in our charge its all the job of JVM. We can only build objects appropriate for garbage collection.

finalize() and gc() Methods

Garbage collector destroys these objects, but the garbage collector is not guaranteed to run at any specific time, so we can explicitly make an object entitled for garbage gathering by applying finalize() and gc() methods.

finalize() Method

Sometime an object will need to perform some definite task before it is vanished such as closing an open connection or release any resources held. To handle such circumstances finalize() method employed.

finalize() method is called by garbage collection thread before collecting object. Its the final opportunity for any object to perform cleanup utility.

gc() Method

This method is used to call garbage collector explicitly. But gc() method does not guarantee that JVM will execute the garbage collection. It only ask the JVM for garbage collection.