Sometimes an object is required to be shared amongst multiple threads. During initialization, the object must remain exclusive to the thread constructing it. However, once the object is initialized, it can be safely published. That is, it can be made visible to other threads. The [Java Memory Model|BB. Definitions#Java Memory Model] allows multiple threads to observe the object after its initialization has begun, but before it has concluded. Consequently, it is important to ensure that a partially initialized object is not published.
This guideline is similar to [CON14-J. Do not let the "this" reference escape during object construction]. In this guideline, a reference to a partially initialized member object instance is published before initialization is over, instead of the {{this}} reference of the current object.
h2. Noncompliant Code Example
This noncompliant code example initializes a {{Helper}} object inside class {{Foo}}.
{code:bgColor=#FFCCCC}
class Foo {
private Helper helper;
public Helper getHelper() {
return helper;
}
public void initialize() {
helper = new Helper(42);
}
}
public class Helper {
private int n;
public Helper(int n) {
this.n = n;
}
// ...
}
{code}
Suppose two or more threads can access the field {{helper}} using the {{getHelper()}} method, and {{initialize()}} has not been called yet. Consequently, all threads will see the {{helper}} field as uninitialized. Later, if one thread calls {{initialize()}}, and another calls {{getHelper()}}, the second thread may either see the {{helper}} reference as {{null}}, observe a fully-initialized {{Helper}} object with the {{n}} field set to 42, or observe a partially-initialized {{Helper}} object with an {{n}} that has not been initialized yet, and which contains the default value {{0}}.
In particular, the [Java Memory Model (JMM)|BB. Definitions#memory model] permits compilers to allocate memory for the new {{Helper}} object and assign it to the {{helper}} field before initializing it. In other words, the compiler can reorder the write to the instance field {{helper}} with the write that initializes the object {{Helper}} (that is, {{this.n = n}}) such that the former occurs first. This introduces a race window during which other threads may see a partially-initialized {{Helper}} object instance.
There is another consideration in that if two threads both call {{initialize()}}, then two {{Helper}} objects will be created, with one eventually being garbage-collected. This is a performance, not a correctness issue.
h2. Compliant Solution (synchronization)
The reference of a partially-constructed object can be prevented from being made visible by using method synchronization.
{code:bgColor=#CCCCFF}
class Foo {
private Helper helper;
public synchronized Helper getHelper() {
return helper;
}
public synchronized void initialize() {
helper = new Helper(42);
}
}
{code}
Synchronizing both methods guarantees that they will never run simultaneously in different threads. If one thread were to call {{initialize()}} just before another thread calls {{getHelper()}}, the synchronized {{initialize()}} method will always finish first. Furthermore, this establishes a [happens-before relationship|BB. Definitions#happens-before order] between the two threads. This guarantees that the thread calling {{getHelper()}} sees the fully initialized {{Helper}} object or none at all ({{helper}} may contain a {{null}} reference). This approach guarantees proper publication for both immutable and mutable members.
h2. Compliant Solution ({{final}} field)
If the {{helper}} field is declared as {{final}}, it is guaranteed to be fully constructed before its reference is made visible.
{code:bgColor=#CCCCFF}
class Foo {
private final Helper helper;
public Helper getHelper() {
return helper;
}
public Foo() {
helper = new Helper(42);
}
}
{code}
However, now the compiler disallows setting the {{helper}} field to a new object using the {{initialize()}} method. Instead, a constructor is required to initialize {{helper}}.
According to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\], section 17.5.2 "Reading Final Fields During Construction":
{quote}
A read of a {{final}} field of an object within the thread that constructs that object is ordered with respect to the initialization of that field within the constructor by the usual happens-before rules. If the read occurs after the field is set in the constructor, it sees the value the {{final}} field is assigned, otherwise it sees the default value.
{quote}
Consequently, the reference to the {{helper}} field should not be published before class {{Foo}}'s constructor has finished its initialization (see [CON14-J. Do not let the "this" reference escape during object construction]).
h2. Compliant Solution ({{final}} field and thread-safe composition)
Some collection classes provide thread-safety of accesses to contained elements. If the {{Helper}} object is inserted into such a collection, it is guaranteed to be fully initialized before its reference is made visible. This compliant solution encases the {{helper}} field in a {{Vector<Helper>}}.
{code:bgColor=#CCCCFF}
class Foo {
private final Vector<Helper> helper;
private Foo() {
helper = new Vector<Helper>();
}
public Helper getHelper() {
if (helper.isEmpty()) {
initialize();
}
return helper.elementAt(0);
}
public synchronized void initialize() {
if (helper.isEmpty()) {
helper.add(new Helper(42));
}
}
}
{code}
The {{helper}} field is declared as {{final}} to guarantee that the vector is created before any accesses take place. It can be suitably initialized using the {{initialize()}} method. The {{initialize}} method is synchronized, and provides a check to ensure that exactly one {{Helper}} object is added to the vector. The {{getHelper()}} needs no synchronization in the general case of returning the {{Helper}}, however, if it is invoked before {{initialize()}}, it must ensure that the vector contains the {{Helper}} instance. Consequently, it invokes {{initialize()}} if the vector is still empty.
h2. Compliant Solution (static initialization)
In this compliant solution, the {{helper}} field is initialized in a {{static}} block. When initialized statically, an object is guaranteed to be fully initialized before its reference is made visible. {mc} cite JLS section here {mc}
{code:bgColor=#CCCCFF}
class Foo {
private static final Helper helper = new Helper(42);
public static Helper getHelper() {
return helper;
}
}
{code}
This requires the {{helper}} field to be declared {{static}}. Although not strictly necessary, it is recommended that the field be declared {{final}} as well to sufficiently document the class's immutability property.
According to JSR-133 \[[JSR-133 04|AA. Java References#JSR-133 04]\], 9.2.3 Static Final Fields:
{quote}
The rules for class initialization ensure that any thread that reads a {{static}} field will be synchronized with the static initialization of that class, which is the only place where {{static final}} fields can be set. Thus, no special rules in the JMM are needed for {{static final}} fields.
{quote}
h2. Compliant Solution (immutable object, {{initializedvolatile}} flagreference)
ThisThe Java compliantmemory solutionmodel usesguarantees a {{volatile}}that any {{initializedfinal}} flag,fields asof recommendedthe by [CON28-J. Prevent partially initialized objects from being used].
{code:bgColor=#CCCCFF}
public class Helper {
private int n;
private volatile boolean initialized; // Defaults to false
public Helper(int n) {
this.n = n;
this.initialized = true;
}
public void doSomething() {
if(!initialized) {
throw new SecurityException("Cannot use partially initialized instance");
}
// ...
}
// ...
}
{code}
This ensures that even if the reference to the {{Helper}} object instance is published before its initialization is over, the instance is unusable. This is because every method within {{Helper}} checks the flag to determine whether the initialization has finished.
h2. Compliant Solution ({{public static}} factory method - immutable object, {{volatile}} reference)
This compliant solution uses a {{public static}} factory method in class {{Helper}} to create a new instance of {{Helper}}. The {{Helper}} instance is created using a {{private}} constructor. The code for class {{Foo}} is the same as the noncompliant code example, except that field {{helper}} is declared as {{volatile}}object will be fully initialized before a published object becomes visible \[[Goetz 06|AA. Java References#Goetz 06]\]. By making {{n}} final, we can render the {{Helper}} class [immutable|BB. Definitions#immutable]. Furthermore, if the {{helper}} field is declared {{volatile}}, the {{Helper}}'s reference is guaranteed to be made visible to any thread that calls {{getHelper()}} after it has been fully initialized.
{code:bgColor=#CCCCFF}
class Foo {
private volatile Helper helper;
public Helper getHelper() {
return helper;
}
public void initialize() {
helper = new Helper.getHelper(42);
}
}
// Immutable Helper
public class Helper {
private final int n;
private Helper(int n) {
this.n = n;
}
public static Helper getHelper() {
Helper helper = new Helper(42);
return helper;
}
// ...
}
{code}
Declaring {{n}} as {{final}} in class {{Helper}} guarantees that the {{Helper}} object will be fully initialized before it is returned to class {{Foo}}; in effect, {{Helper}} is made immutable. This is useful when {{getHelper()}} can be invoked by untrusted callers. Declaring field {{helper}} public Helper(int n) {
this.n = n;
}
// ...
}
{code}
An alternative is to use a {{public static}} factory method in class {{Helper}} to create a new instance of {{Helper}}. The {{Helper}} instance is created using a {{private}} constructor.
{code:bgColor=#CCCCFF}
// Immutable Helper
public class Helper {
private final int n;
private Helper(int n) {
this.n = n;
}
public static Helper getHelper() {
Helper helper = new Helper(42);
return helper;
}
// ...
}
{code}
This compliant solution requires that {{helper}} be declared as {{volatile}} ensures that the reference toand class {{helperHelper}} is made visible to other threads (see [CON09-J. Ensure be immutable. If it were not immutable, the code would violate [CON11-J. Do not assume that declaring an object volatile guarantees visibility of shared references to immutable objects]).
h2. Compliant Solution (immutable object, {{volatile}} reference)
The Java memory model guarantees that any {{final}} fields of the object will be fully initialized before a published object becomes visible \[[Goetz 06|AA. Java References#Goetz 06]\]. By making {{n}} final, we can render the {{Helper}} class [immutable|BB. Definitions#immutable]. Furthermore, if the {{helper}} field is declared its members] and additional synchronization would be required to fix it (see the next compliant solution). And if it the {{helper}} field were not {{volatile}}, it would violate [CON09-J. Ensure visibility of shared references to immutable objects]. See this rule for more information on how to safely publish immutable objects.
h2. Compliant Solution (mutable thread-safe object, {{volatile}}, thereference)
If {{Helper}}'s referenceis ismutable, guaranteed to be made visible to any thread that calls {{getHelper()}} after it has been fully initialized.but thread-safe, it can be safely published by declaring the {{helper}} field in class {{Foo}} as {{volatile}}.
{code:bgColor=#CCCCFF}
class Foo {
private volatile Helper helper;
public Helper getHelper() {
return helper;
}
public void initialize() {
helper = new Helper(42);
}
}
// Immutable Mutable but thread-safe Helper
public class Helper {
private finalvolatile int n;
public Helper(int n) {
this.n = n;
}
public synchronized void setN(int nvalue) {
this.n = nvalue;
}
// ...
}
{code}
This compliant solution requires that {{helper}} be both {{volatile}} and immutable. If it is not immutable, the code would violate [CON11-J. Do not assume that declaring an object volatile guarantees visibility of its members] and additional synchronization would be required to fix it. And if it the {{helper}} field were not {{volatile}}, it would violate [CON09-J. Ensure visibility of shared references to immutable objects]. See this rule for more information on how to safely publish immutable objects.
Primitive types can also be safely published by publishing an atomic reference to the corresponding boxed type. For instance, an {{int}} field can be safely published by publishing an atomic reference to the equivalent {{Integer}} using {{java.util.concurrent.atomic.AtomicReference<Integer>}}.
h2. Compliant Solution (mutable thread-safe object, {{volatile}} reference)
If {{Helper}} is mutable, but thread-safe, it can be safely published by declaring the {{helper}} field in class {{Foo}} as {{volatile}}.
{code:bgColor=#CCCCFF}
class Foo {
private volatile Helper helper;
public Helper getHelper() {
return helper;
}
public void initialize() {
helper = new Helper(42);
}
}
// Mutable but thread-safe Helper
public class Helper {
private volatile int n;
public Helper(int n) {
this.n = n;
}
public synchronized void setN(int value) {
n = value;
}
}
{code}
Because the state of the {{Helper}} object can be changed after its construction, additional locking is necessary to ensure all threads see the most recent value of {{n}} after the initial publication. See [CON11-J. Do not assume that declaring an object volatile guarantees visibility of its members] for more information. This is typically the case when a mutable member object is expected to continually publish its most recent state when its reference is declared {{volatile}}. Consequently, in this compliant solution, the {{setN()}} method needs to be synchronized.
The field {{n}} must also be declared as {{volatile}} so that a happens-before relationship is established between the initialization of {{n}} and the write of {{Helper}} to the field {{helper}}.
In the absence of proper synchronization in class {{Helper}}, the use of {{volatile}} in class {{Foo}} guarantees the visibility of only the initial publication of {{Helper}} and not of subsequent state changes. Consequently, {{volatile}} is not useful for publishing thread-unsafe objects. Because the state of the {{Helper}} object can be changed after its construction, additional locking is necessary to ensure all threads see the most recent value of {{n}} after the initial publication. See [CON11-J. Do not assume that declaring an object volatile guarantees visibility of its members] for more information. This is typically the case when a mutable member object is expected to continually publish its most recent state when its reference is declared {{volatile}}. Consequently, in this compliant solution, the {{setN()}} method needs to be synchronized.
The field {{n}} must also be declared as {{volatile}} so that a happens-before relationship is established between the initialization of {{n}} and the write of {{Helper}} to the field {{helper}}. This is in compliance with [CON11-J. Do not assume that declaring an object volatile guarantees visibility of its members].
In the absence of proper synchronization in class {{Helper}}, the use of {{volatile}} in class {{Foo}} guarantees the visibility of only the initial publication of {{Helper}} and not of subsequent state changes. Consequently, {{volatile}} is not useful for publishing thread-unsafe objects.
h2. Exceptions
*EX1:* This excption uses a {{volatile}} {{initialized}} flag, as recommended by [CON28-J. Prevent partially initialized objects from being used].
{code:bgColor=#CCCCFF}
public class Helper {
private int n;
private volatile boolean initialized; // Defaults to false
public Helper(int n) {
this.n = n;
this.initialized = true;
}
public void doSomething() {
if(!initialized) {
throw new SecurityException("Cannot use partially initialized instance");
}
// ...
}
// ...
}
{code}
This ensures that even if the reference to the {{Helper}} object instance is published before its initialization is over, the instance is unusable. This is because every method within {{Helper}} checks the flag to determine whether the initialization has finished. This approach is more useful when the caller ({{Foo}}) is untrusted and consequently, may not declare the {{helper}} field as {{volatile}}.
h2. Risk Assessment
Failing to synchronize access to shared mutable data can cause different threads to observe different states of the object or a partially initialized object.
|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| CON26-J | medium | probable | medium | {color:#cc9900}{*}P8{*}{color} | {color:#cc9900}{*}L2{*}{color} |
h3. Automated Detection
TODO
h3. Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the [CERT website|https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+CON26-J].
h2. References
\[[API 06|AA. Java References#API 06]\]
\[[Bloch 01|AA. Java References#Bloch 01]\] Item 48: "Synchronize access to shared mutable data"
\[[Goetz 06|AA. Java References#Goetz 06]\] Section 3.5.3 "Safe Publication Idioms"
\[[Goetz 07|AA. Java References#Goetz 07]\] Pattern #2: "one-time safe publication"
\[[JPL 06|AA. Java References#JPL 06]\], 14.10.2. Final Fields and Security:
\[[Pugh 04|AA. Java References#Pugh 04]\]
----
[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!|FIO36-J. Do not create multiple buffered wrappers on an InputStream] [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!|09. Input Output (FIO)] [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!|09. Input Output (FIO)]
|