I think I’ve found an error in some of my code, though it doesn’t appear to rear its head in all situations. I’m hoping someone smarter than me can definitively say “Yes, this is an error”, and better yet, to suggest an another alternative to my implementation.
I believe the source of the error is how the static fields of two classes are initialized; one (in FooClass) is initialized by referring to the other’s field, and one (in MyUtility) is initialized by creating an object of type Foo. Sorry that sounds off; explanation was never my strong point.
I’ve spent the better part of a day trying to reduce the problem, and have something runnable that appears to demonstrate the problem.
public class Tester {
static class FooClass {
static final FooClass ITS_FOO = MyUtility.MY_FOO;
}
static class MyUtility {
static final FooClass MY_FOO = new FooClass();
static FooClass create() {
return new FooClass();
}
}
public static void main(String[] args) {
System.out.println("utility's: " + MyUtility.create()); // Line "A"
System.out.println("class's: " + FooClass.ITS_FOO); // Line "B"
}
}
I realize this design looks odd, but won’t try to justify it much (the real code is structured “oddly” too, but within separate classes with different visibility etc). I would definitely appreciate suggestions for better ways to do this.
The gist of the problem (at least with this program) is that the FooClass.ITS_FOO field is null when line B executes. If I switch the order of lines A and B, neither of the fields are null.
I’ve seen questions like In what order do static initializer blocks in Java run?, but neither that nor the Java Language Spec appear to describe how this kind of mutually referential initialization is done.
Unfortunately, this sample is so far removed from our real implementation that I’ll probably spend the same amount of time translating any solution back, but that will be worth it to get some explanation.
Yes, if you force
FooClassto initialize first, then that will triggerMyUtilityinitializing. The initializer forMY_FOOwill proceed becauseFooClassis already initializing in this thread, soMY_FOOwill be non-null.On the other hand, if you observe
ITS_FOOfrom theFooClassconstructor (currently just defaulted), you’ll see it’s null there…This behaviour is well documented in the spec – the section you’ve linked to gives all the details – but basically it’s a really bad idea to have two types whose static initializers refer to each other. Don’t try to fix it in subtle ways: get rid of the dependency. I realize this may be a pain, but really, it’s not worth thinking about any other fix.
One way of performing that fix may be to extract a third type with a static initializer which doesn’t depend on any other types, and which both of the other types can depend on.
Of course, doing less in your static initializers is also helpful 🙂