Header Ads

What is Circular Reference in Java

In my last post I have told already how Old Fashioned Coding Style May Help Garbage Collector to Reclaim Memory Quickly.

I have shown that how our coding style can help JVM to free up memory easily.


But Bilkis pointed out correctly about circular reference. Thanks Bilkis!!! yes you are very correct.


Setting every object to null is not correct. If proper observation is not given this may lead to circular reference.


Let us understand what is circular reference:

Circular reference is such combination of objects where one object has a reference to another and second object has a reference to the first. For this case garbage collector can not operate collection process on both the object.

The worst part of it ,if there is no external reference to either object. These object stays in the memory till program ends.

Here Class1 has a reference to Class2 and Class2 has a reference to Class1.
A call is made from Main. In this case Garbage collector program runs perfect.




Now let us cut the call from Main..
This will create a circular reference problem.
As per Wiki--
circular reference is a series of references where the last object references the first, resulting in a closed loop.A circular reference is not to be confused with the logical fallacy of a circular argument. Although a circular reference will often be unhelpful and reveal no information, such as two entries in a book index referring to each other, it is not necessarily so that a circular reference is of no use. Dictionaries, for instance, must always ultimately be a circular reference since all words in a dictionary are defined in terms of other words, but a dictionary nevertheless remains a useful reference. Sentences containing circular referents can still be meaningful;
Let me show how circular reference can be created..
This is the first class which will have a reference to second class


public class firstClass {
secondClass sc;
public firstClass() {
sc=new secondClass();
}
}
Now let us create a second class which has a reference to first class


public class secondClass {
firstClass fc;
secondClass() {
fc=new firstClass();
}
}
Now let us create the final or last class which is calling the first class..
public class CallingClass {


public static void main(String[] args) {

firstClass fc1=new firstClass();
//some code

}

}
Problem happens when we cut the connection from calling class...
public class CallingClass {


public static void main(String[] args) {

firstClass fc1=new firstClass();
//some code
fc1=null;
}
}
The last line--
fc1=null;
will create circular reference..
Be careful here.
Powered by Blogger.