...
With the cycle broken, the initial values will always be A.a = 2
and B.b = 3
, regardless of initialization order.
Noncompliant Code Example
This noncompliant code example tries to initialize a static variable in one class using a static method in a second class, but that method in turn relies on a static method in the first class.
Code Block | ||||
---|---|---|---|---|
| ||||
class A {
public static int a = B.b();
public static int c() {return 1;}
}
class B {
public static int b() {return A.c();}
}
|
This code correctly initializes A.a
to 1 using the Oracle JVM, regardless of whether A
or B
is loaded first. However, the JLS does not guarantee that A.a
to be properly initialized. Furthermore, the initialization cycle makes this sytem harder to maintain, and more likely to break in surprising ways when modified.
Compliant Solution
This compliant solution moves the c()
method into class B
, breaking the cycle:
Code Block | ||||
---|---|---|---|---|
| ||||
class A {
public static int a = B.b();
}
class B {
public static int b() {return B.c();}
public static int c() {return 1;}
}
|
Risk Assessment
Initialization cycles may lead to unexpected results.
...