Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot (vkp) v1.0

Wiki Markup
According to the Java Language Specification \[[JLS 2005|AA. Java References#JLS 05]\], section 8.3.2.1 "Initializers for Class Variables":

...at run time, static variables that are final and that are initialized with compile-time constant values are initialized first.

While this statement typically holds, it can be misleading as it does not account for instances that use values of static final fields initialized at a later stage. Even if a field is static final, it is not necessarily initialized before being read.

Noncompliant Code Example

This noncompliant code example contrives to calculate the account balance by subtracting the processing fee from the deposited amount, but fails to do so. The Cycle class object c is instantiated before the deposit field gets initialized.

Code Block
bgColor#FFcccc
public class Cycle {
  private static final Cycle c = new Cycle();
  private final int balance;
  private static final int deposit =  (int) (Math.random() * 100); // Random deposit

  public Cycle(){
    balance = deposit - 10; // Subtract processing fee
  }

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

As a result, the constructor Cycle() is invoked which computes the balance based on the initial value of deposit (0) rather than the random value. As a result, the balance always remains -10.

Wiki Markup
According to the Java Language Specification \[[JLS 2005|AA. Java References#JLS 05]\], section 12.4 "Initialization of Classes and Interfaces":

Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class.

Wiki Markup
This statement asserts that the presence of a {{static}} field triggers the initialization of a class, however, in this example, a recursive attempt is being made to initialize the class already. Because such recursive attempts are ignored by the JVM, the default value of {{deposit}} is {{0}} during the initialization. \[[Bloch 2005|AA. Java References#Bloch 05]\]

Compliant Solution

This compliant solution changes the initialization order of the class Cycle so that the fields meant to be used in computations get duly initialized.

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);	
  }
}

As initialization cycles can become insidious when many classes are involved, proper care must be taken to inspect the control flow.

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 2008|AA. Java References#Findbugs 08]\].

Code Block
bgColor#FFcccc
public class CircularClassInit {
  static class InnerClassSingleton extends CircularClassInit {
    static final InnerClassSingleton singleton = new InnerClassSingleton();
  }
  static final 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 final 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 2008|AA. Java References#Findbugs 08]\]. Also see the related guideline [MSC08-J. Avoid cyclic dependencies between packages].

Risk Assessment

Initialization cycles may lead to unexpected results.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC07- J

low

unlikely

medium

P2

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Other Languages

This rule appears in the C++ Secure Coding Standard as DCL14-CPP. Avoid assumptions about the initialization order between translation units.

References

Wiki Markup
\[[JLS 2005|AA. Java References#JLS 05]\] Sections [8.3.2.1, Initializers for Class Variables|http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.3.2.1]; [12.4, Initialization of Classes and Interfaces|http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.4]
  Puzzle 49: Larger Than Life
\[[MITRE 2009|AA. Java References#MITRE 09]\] [CWE ID 665|http://cwe.mitre.org/data/definitions/665.html] "Improper Initialization"


MSC06-J. Avoid memory leaks      49. Miscellaneous (MSC)      MSC08-J. Avoid cyclic dependencies between packages