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.