Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: rewrote a lot

...

This noncompliant code example uses declares two classes with static variables that whose values depend on each other. When seen together, the cycle is obvious, but the cycle can be easily missed when the classes are viewed separately.

...

Code Block
bgColor#FFcccc
class B {
    static public final int b = A.a + 1;
    // ...
}

The values of initialization order of the classes can vary and consequently compute different values for A.a and B.b can vary, depending on which class gets initialized first. If . When class A is initialized first, then A.a will have the value 2 and B.b will have the value 1. The These values will be reversed if when class B is initialized first.

Compliant Solution (inter-class cycle)

This compliant solution eliminates breaks the inter-class cycle by eliminating one of the dependencies.

Code Block
bgColor#ccccff
class A {
    static public final int a = 2;
    // ...
}

// class B unchanged: b = A.a + 1

With the cycle broken, the initial values will always be A.a = 2 and B.b = 3, no matter which class gets initialized firstregardless of initialization order.

Risk Assessment

Initialization cycles may lead to unexpected results.

...