Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added nce/cs

...

Code Block
bgColor#ccccff
public class Cycle {
  private final int balance;
  private static final int deposit =  (int) (Math.random() * 100); //random deposit
  private static final Cycle c = new Cycle();  //inserted after initialization of required fields
  public Cycle(){
    balance = deposit - 10; //subtract processing fee
  }

  public static void main(String[] args) {
    System.out.println("The account balance is: " + c.balance);	
  }
}

Noncompliant Code Example

Wiki Markup
This noncompliant code example uses an inner class that extends the outer class. The outer class in turn, uses the static instance of the inner class. This results in a circular initialization issue \[[Findbugs 08|AA. Java References#Findbugs 08]\].

Code Block
bgColor#FFcccc

public class CircularClassInit {
  static class InnerClassSingleton extends CircularClassInit {
    static InnerClassSingleton singleton = new InnerClassSingleton();
  }
  static CircularClassInit foo = InnerClassSingleton.singleton;
}

Compliant Solution

This compliant solution removes the instance of the inner class from the outer class.

Code Block
bgColor#ccccff

public class CircularClassInit {
  static class InnerClassSingleton extends CircularClassInit {
    static InnerClassSingleton singleton = new InnerClassSingleton();
  }
}

Wiki Markup
Notably, class initialization cycles can also occur because of circularity in the code present within the {{static}} initializers of two or more classes \[[Findbugs 08|AA. Java References#Findbugs 08]\]. Also see the related guideline [MSC02-J. Avoid cyclic dependencies between packages].

Risk Assessment

Initialization cycles may lead to unexpected results.

...