java - Static initializer runs after the constructor, why? -
i have 2 classes:
class a:
public class { static b b = new b(); static { system.out.println("a static block"); } public a() { system.out.println("a constructor"); } }
class b:
public class b { static { system.out.println("b static block"); new a(); } public b() { system.out.println("b constructor"); } }
i create main class creates new a:
public class main { public static void main(string[] args) { new a(); } }
the output is:
b static block constructor b constructor static block constructor
as can see, constructor of invoked before static initializer.
i understand got cyclic dependency created under impression static initializer should run before constructor.
what reason happen (technically in java implementation) ?
is recommended avoid static initializers ?
static b b = new b();
is before
static { system.out.println("a static block"); }
so require b instance initialized before print "a static block"
.
and initializing b class means need create a instance. there's no way "a static block" printed before instance constructed.
yes, static initialization of launched before constructor launched but, apart deadlocking, there no other solution sequence require.
note warning in the specification :
because java programming language multithreaded, initialization of class or interface requires careful synchronization, since other thread may trying initialize same class or interface @ same time. there possibility initialization of class or interface may requested recursively part of initialization of class or interface; example, variable initializer in class might invoke method of unrelated class b, might in turn invoke method of class a. implementation of java virtual machine responsible taking care of synchronization , recursive initialization using following procedure [the doc goes on complete procedure]
a best practice, in java in other languages, avoid cyclic dependencies resolution may hard predict.
Comments
Post a Comment