According to the The Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\], Section 12 (JLS), §12.4, "Initialization of Classes and Interfaces" [JLS 2005]: Wiki Markup
Initialization of a class consists of executing its
static
initializers and the initializers forstatic
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 In other words, the presence of a {{static}} field triggers the initialization of a class. However, a static field might depend on the initialization of a class, and might create an initialization cycle. The Java Language Specification also states: (\[[JLS 2005|AA. Bibliography#JLS 05]\], Section 8.3.2.1, "Initializers for Class Variables" )[JLS 2005]: Wiki Markup
At ...at run time,
static
variables that arefinal
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 This statement does not apply to instances that use values of static final fields that are initialized at a later stage. Even if Declaring a field is to be static final , is insufficient to guarantee that it is not necessarily fully initialized before being read.
Programs in general should—and security-sensitive programs must—eliminate all class initialization cycles.
Noncompliant Code Example (
...
Intraclass Cycle)
In this This noncompliant code example , a recursive attempt is being made to initialize the class, creating an initialization cycle. contains an intraclass initialization cycle:
Code Block | ||
---|---|---|
| ||
public class Cycle { private final int balance; 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); } } |
Wiki Markup |
---|
Because such recursive attempts are ignored by the JVM, the default value of {{deposit}} is {{0}} during the initialization \[[Bloch 2005|AA. Bibliography#Bloch 05]\]. The code tries 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 is initialized. 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 is always equal to {{-10}}. |
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 meant to be used in computations get duly 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.
Code Block | ||
---|---|---|
| ||
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 Such initialization cycles can become insidious when many classes fields are involved, proper care must be taken to inspect the control flowso 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 uses declares two classes with static variables that whose values depend on each other. When seen together, the The cycle is obvious , but the cycle can be easily missed when the classes are viewed when the classes are seen together (as here) but is easy to miss when viewing the classes separately.
Code Block | ||
---|---|---|
| ||
class A { public static public final int a = B.b + 1; // ... } | ||
Code Block | ||
| ||
class B { public static public final int b = A.a + 1; // ... } |
The values of initialization order of the classes can vary, causing computation of 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 (
...
Interclass Cycle)
This compliant solution eliminates one of the dependencies.breaks the interclass cycle by eliminating the dependency of A
on B
:
Code Block | ||
---|---|---|
| ||
class A { public static public final int a = 2; // ... } // class B unchanged: { 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
, no matter which class gets initialized first. 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:
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 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:
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.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|
DCL00-J |
Low |
Unlikely |
Medium | P2 | L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Other Languages
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
CodeSonar |
| JAVA.STRUCT.UA JAVA.STRUCT.UA.DEFAULT | Useless Assignment (Java) Useless Assignment to Default (Java) | ||||||
Parasoft Jtest |
| CERT.DCL00.ACD | Ensure that files do not contain cyclical dependencies | ||||||
PVS-Studio |
| V6050 | |||||||
SonarQube |
| Classes should not access their own subclasses during initialization |
Related Guidelines
...
Initialization of Variables [LAV] | |
CWE-665, Improper Initialization |
Bibliography
Puzzle 49, "Larger than Life" | |
[JLS 2005] |
Bibliography
...
...
...
...
§12.4, "Initialization of Classes and Interfaces" | |
[Seacord 2015] | DCL00-J. Prevent class initialization cycles LiveLesson |
...
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. Bibliography#MITRE 09]\] [CWE ID 665|http://cwe.mitre.org/data/definitions/665.html] "Improper Initialization"MSC06-J. Avoid memory leaks 49. Miscellaneous (MSC) DCL13-J. Avoid cyclic dependencies between packages