Static initializer runs after the constructor, why?

戏子无情 提交于 2019-11-28 21:13:25
static B b = new B();

is before

static {
     System.out.println("A static block");
}

So you require that the B instance be initialized before you print "A static block".

And initializing the B class means you need to create a A instance. So there's no way for "A static block" to be printed before the A instance is constructed.

Yes, the static initialization of A is launched before the constructor is launched but, apart deadlocking, there would be no other solution to the sequence you require.

Note the warning in the specification :

Because the Java programming language is multithreaded, initialization of a class or interface requires careful synchronization, since some other thread may be trying to initialize the same class or interface at the same time. There is also the possibility that initialization of a class or interface may be requested recursively as part of the initialization of that class or interface; for example, a variable initializer in class A might invoke a method of an unrelated class B, which might in turn invoke a method of class A. The implementation of the Java virtual machine is responsible for taking care of synchronization and recursive initialization by using the following procedure [the doc goes on with the complete procedure]

A best practice, in Java as in other languages, is basically to avoid cyclic dependencies as their resolution may be very hard to predict.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!