Skip to end of metadata
Go to start of metadata

According to The Java Language Specification (JLS), §12.4, "Initialization of Classes and Interfaces" [JLS 2005]:

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

Therefore, the presence of a static field triggers the initialization of a class. However, the initializer of a static field could depend on the initialization of another class, possibly creating an initialization cycle.

The JLS also states in §8.3.2.1, "Initializers for Class Variables" [JLS 2005]:

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

This statement does not apply to instances that use values of static final fields that are initialized at a later stage. Declaring a field to be static final is insufficient to guarantee that it is fully initialized before being read.

Programs in general should—and security-sensitive programs must—eliminate all class initialization cycles.

Noncompliant Code Example (Intraclass Cycle)

This noncompliant code example contains an intraclass initialization cycle:

public class Cycle {
  private final int balance;
  private static final Cycle c = new Cycle();
  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);
  }
}

The Cycle class declares a private static final class variable, which is initialized to a new instance of the Cycle class. Static initializers are guaranteed to be invoked once before the first use of a static class member or the first invocation of a constructor.

The programmer's intent is to calculate the account balance by subtracting the processing fee from the deposited amount. However, the initialization of the c class variable happens before the runtime initialization of the deposit field because it appears lexically before the initialization of the deposit field. Consequently, the value of deposit seen by the constructor, when invoked during the static initialization of c, is the initial value of deposit (0) rather than the random value. As a result, the balance is always computed to be -10.

Step 3 of the detailed initialized procedure described in JLS §12.4.2 [JLS 2014] permits implementations to ignore the possibility of such recursive initialization cycles.

Compliant Solution (Intraclass Cycle)

This compliant solution changes the initialization order of the class Cycle so that the fields are initialized without creating any dependency cycles. Specifically, the initialization of c is placed lexically after the initialization of deposit so that it occurs temporally after deposit is fully initialized.

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

Such initialization cycles become insidious when many fields are involved, so it is important to ensure that the control flow lacks such cycles.

Although this compliant solution prevents the initialization cycle, it depends on declaration order and is consequently fragile; later maintainers of the software may be unaware that the declaration order must be maintained to preserve correctness. Consequently, such dependencies must be clearly documented in the code.

Noncompliant Code Example (Interclass Cycle)

This noncompliant code example declares two classes with static variables whose values depend on each other. The cycle is obvious when the classes are seen together (as here) but is easy to miss when viewing the classes separately.

class A {
  public static final int a = B.b + 1;
  // ...
}

class B {
  public static final int b = A.a + 1;
  // ...
}

The initialization order of the classes can vary, causing computation of different values for A.a and B.b. When class A is initialized first, A.a will have the value 2, and B.b will have the value 1. These values will be reversed when class B is initialized first.

Compliant Solution (Interclass Cycle)

This compliant solution breaks the interclass cycle by eliminating the dependency of A on B:

class A {
  public static final int a = 2;
  // ...
}

class B {
  public static final int b = A.a + 1;
  // ...
}

With the cycle broken, the initial values will always be A.a = 2 and B.b = 3 regardless of initialization order.

Noncompliant Code Example

The programmer in this noncompliant code example attempts 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:

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 A.a to be properly initialized. Furthermore, the initialization cycle makes this system 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:

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.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL00-J

Low

Unlikely

Medium

P2

L3

Automated Detection

ToolVersionCheckerDescription
CodeSonar
5.0p0

FB.STYLE.IC_INIT_CIRCULARITY

Initialization circularity
Parasoft Jtest
10.3
GLOBAL.ACDImplemented
SonarQube
6.7

S2390

Classes should not access their own subclasses during initialization

Related Guidelines

Bibliography



3 Comments

  1. Does the following code have an initialization cycle?

    class A {
        public static int a = B.b();
        public static int c() {return 1;}
    }
    
    class B {
        public static int b() {return A.c();}
    }
    

    It appears to me that it does, yet I can't make the code misbehave. It always sets A.a to 1 no matter which class is initialized first. This happens whether a is final or not.

    Perhaps this code is a maintenance problem, but I don't think the code behaves oddly. So does this code violate this rule?

    1. I am probably wrong here, but could it be due to B.b() being a method call? From playing around with a similar code fragment, it seems like the following is occurring

      1. Enter B.b(), try to call A.c() but find that A is not initialized
      2. Begin initialization of A, A.a calls B.b() which now has a valid reference to A.c() so it gets the proper value of 1
      3. After A has been initialized, the original B.b() call continues and returns A.c()

      If either B.b is changed to a static field set to A.c(), or A.c() becomes a static field with some constant value then we get the expected faulty behavior.

      1. No, I suspect you are right...that B.b() being a method call makes this program technically safe on Oracle's JVM. That said, I would still consider my example code noncompliant even if it behaves correctly, because:

        1. There is no guarentee that it behaves correctly on all possible JVMs (even if it behaves correctly on all versions on Sun/Oracle JVM)
        2. The code is harder to maintain b/c of the init cycle. It may behave properly now, but break in surprising ways when modified.

        I can think of one example that might merit an exception, (if B was a private inner class of A, then the code is always safe b/c B can't be initialized before A). But that code is still a maintenance headache, so I don't want to add it.