Monday 10 October 2016

How to resolve Circular Dependency Problem

What is Circular Dependency Problem?
Circular dependency is a relation between two or more modules which either directly or indirectly depend on each other to function properly. Let me explain with an example.

Suppose there are two classes A and B. A is dependent on B and B is dependent on A.
public class A {
 private B b;
 
 public A(){
  this.b = new B();
 }
}

public class B {
 private A a;
 
 public B(){
  this.a = new A();
 }
}
As you see the constructor of class ‘A’, it initialize object of class B, that means A is dependent on B.

As you see the constructor of class ‘B’, it initialize object of class A, that means B is dependent on A.

A is dependent on B and B is dependent on A. This is called circular dependency problem.

What happen if you try to instantiate class A (or) B?
Let us try to define object for class A, the constructor of class A calls the constructor of class B. The constructor of class B calls the constructor of class A. This is an infinite recursion call, finally application end up in  StackOverflowError.
public class CircularDependencyDemo {
 public static void main(String args[]){
  A obj  = new A();
 }
}

Run above application, you will end up in StackOverflowError.
Exception in thread "main" java.lang.StackOverflowError
 at B.<init>(B.java:5)
 at A.<init>(A.java:6)
 at B.<init>(B.java:6)
 at A.<init>(A.java:6)
 at B.<init>(B.java:6)
 at A.<init>(A.java:6)

How to resolve circular dependency problem?
There are two ways to resolve this problem.
a.   Removing the dependency from constructor definition
b.   Point the circular dependency to current object

Removing the dependency from constructor definition
Define the dependencies using setter methods like below.
public class A {
 private B b;

 public A() {

 }

 public void setB(B b) {
  this.b = b;
 }

}

public class B {
 private A a;

 public B() {

 }

 public void setA(A a) {
  this.a = a;
 }

}

Point the circular dependency to current object
Update classes A and B like below.
public class A {
 private B b;

 public A() {
  b = new B(this);
 }

}

public class B {
 private A a;

 public B(A a) {
  this.a = a;
 }

}






No comments:

Post a Comment