java循环依赖,java类中的循环依赖

I have the following classes.

public class B

{

public A a;

public B()

{

a= new A();

System.out.println("Creating B");

}

}

and

public class A

{

public B b;

public A()

{

b = new B();

System.out.println("Creating A");

}

public static void main(String[] args)

{

A a = new A();

}

}

As can be clearly seen, there is a circular dependency between the classes. if I try to run class A, I eventually get a StackOverflowError.

If a dependency graph is created, where nodes are classes, then this dependency can be easily identified (at least for graphs with few nodes). Then why does the JVM not identify this, at least at runtime? Instead of a throwing StackOverflowError, JVM can at least give a warning before starting execution.

[Update] Some languages cannot have circular dependencies, because then the source code will not build. For example, see this question and the accepted answer. If circular dependency is a design smell for C# then why is it not for Java? Only because Java can(compile code with circular dependencies)?

[update2] Recently found jCarder. According to the website, it finds potential deadlocks by dynamically instrumenting Java byte codes and looking for cycles in the object graph. Can anyone explain how does the tool find the cycles?

解决方案

The constructor of your class A calls the constructor of class B. The constructor of class B calls the constructor of class A. You have an infinite recursion call, that's why you end up having a StackOverflowError.

Java supports having circular dependencies between classes, the problem here is only related to constructors calling each others.

You can try with something like:

A a = new A();

B b = new B();

a.setB(b);

b.setA(a);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值