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,. thatThat is, it can be made visible to other threads.
The Java Memory Model permits athe compiler and the runtime to modifychange the order of execution instructionsof program statements in such a way that a seemingly innocuous publication results in multiple threads observing the object after its initialization has begun, but before it has concluded.
This guideline is similar to [CON14-J. Do not let the "this" reference escape during object construction]. The difference is that in this guideline, a reference to a partially constructed member object instance is published instead of the {{this}} reference of the current object, before initialization is over.
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 have access to the same {{Foo}} object through the use of the {{getHelper()}} method, and {{initialize()}} has not been called yet. BothAll threads will see the {{helper}} field as uninitialized. Subsequently, if one thread calls {{initialize()}}, and the other 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 yet been initialized, and still containscontaining the default value of {{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. This introduces a race window during which other threads may see a partially-initialized {{helperHelper}} object instance.
h2. NoncompliantCompliant Code ExampleSolution (immutable)
If the {{Helpersynchronized}})
The classreference is [immutable|BB. Definitions#immutable], then it can notof a partially-constructed object can be changedprevented afterfrom itbeing ismade initialized.visible However,by thisusing does not prevent it from being read before it is completely initialized.
\[[JPL 06|AA. Java References#JPL 06]\], 14.10.2. Final Fields and Security, states:
{quote}
... indeed you can use final fields to define immutable objects. There is a common misconception that shared access to immutable objects does not require any synchronization because the state of the object never changes. This is a misconception in general because it relies on the assumption that a thread will be guaranteed to see the initialized state of the immutable object, and that need not be the case. The problem is that, while the shared object is immutable, the reference used to access the shared object is itself shared and often mutable. Consequently, a correctly synchronized program must synchronize access to that shared reference, but often programs do not do this, because programmers do not recognize the need to do it. For example, suppose one thread creates a String object and stores a reference to it in a static field. A second thread then uses that reference to access the string. There is no guarantee, based on what we've discussed so far, that the values written by the first thread when constructing the string will be seen by the second thread when it accesses the string.
{quote}
{code:bgColor=#CCCCFF}
public class Helper {
private final int n;
public Helper(int n) {
this.n = n;
}
// ...
}
{code}
h2. Compliant Solution ({{volatile}})
If the {{helper}} field is declared as {{volatile}}, it is guaranteed to be fully constructed (that is, its fields are properly initialized) before the reference is made visible.
{code:bgColor=#CCCCFF}
class Foo {
private volatile Helper helper;
public Helper getHelper() {
return helper;
}
public void initialize() {
helper = new Helper(42);
}
}
{code}
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>}}.
Note that if the Helper object is mutable or not thread-safe, you must add additional locking to protect its fields from being modified concurrently by multiple threads as well. See [CON11-J. Do not assume that declaring an object volatile guarantees visibility of its members] for more information.
Also, if the {{Foo}} object allows you to change what the {{helper}} fields points to, you will want additional locking to ensure that this ability does not lead to data races.
h2. Compliant Solution ({{final}})
If the {{helper}} field is declared as {{final}}, then it is guaranteed to be fully constructed before its reference is made visible.method synchronization.
{code:bgColor=#CCCCFF}
class Foo {
private final Helper helper;
public Helper getHelper() {
return helper;
}
public Foo() {
helper = new Helper(42);
}
}
{code}
However, the compiler now disallows setting the {{helper}} field to a new object using the {{initialize()}} method. Instead, a constructor must be used 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.
Note that if the Helper object is mutable or not thread-safe, you must add additional locking to protect its fields from being modified concurrently by multiple threads as well. See [CON11-J. Do not assume that declaring an object volatile guarantees visibility of its members] for more information.
h2. Compliant Solution ({{synchronized}})
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, fully initializing the {{Helper}} object on its way. This forbids {{getHelper()}} from retrieving a {{Helper}} object that is partially initialized.
Note that if the Helper object is mutable or not thread-safe, you must add additional locking to protect its fields from being modified concurrently by multiple threads as well. See [CON11-J. Do not assume that declaring an object volatile guarantees visibility of its members] for more information.
h2. Compliant Solution (thread-safe composition)
Some collection classes provide thread-safety of accesses to contained elements. If the {{helper}} field is contained in such a collection, the {{Helper}} object is guaranteed to be fully initialized before its reference is made visible. This compliant solution encases the {{helper}} field in a {{Vector}}.
{code:bgColor=#CCCCFF}
class Foo {
private Vector<Helper> helper;
public Helper getHelper() {
return helper.elementAt(0);
}
public void initialize() {
helper = new Vector<Helper>();
helper.add(new Helper(42));
}
}
{code}
Note that if the Helper object is mutable or not thread-safe, you must add additional locking to protect its fields from being modified concurrently by multiple threads as well. See [CON11-J. Do not assume that declaring an object volatile guarantees visibility of its members] for more information.
Also, if the {{Foo}} object allows you to change what the {{helper}} fields points to, you will want additional locking to ensure that this ability does not lead to data races.
h2. Compliant Solution (static initialization)
In this compliant solution,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, fully initializing the {{Helper}} object on its way. This forbids {{getHelper()}} from retrieving a {{Helper}} object that is partially initialized. This approach guarantees proper publication for both immutable and mutable members.
h2. Compliant Solution (thread-safe member declared {{volatile}})
If the {{helper}} field is declared as {{volatile}}, it is guaranteed to be fully constructed (that is, its fields are properly initialized) before the reference is made visible. This requires the {{Helper}} object to be thread-safe.
{code:bgColor=#CCCCFF}
class Foo {
private volatile Helper helper;
public Helper getHelper() {
return helper;
}
public void initialize() {
helper = new Helper(42);
}
}
// Immutable Helper
public class Helper {
private final int n;
public Helper(int n) {
this.n = n;
}
// ...
}
{code}
Note that if the Helper object were not thread-safe (or immutable), additional locking would be necessary to ensure all threads see the most recent object state. See [CON11-J. Do not assume that declaring an object volatile guarantees visibility of its members] for more information.
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 ({{final}})
If the {{helper}} field is declared as {{final}}, then 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, the compiler now disallows setting the {{helper}} field to a new object using the {{initialize()}} method. Instead, a constructor must be used 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.
h2. Compliant Solution (thread-safe composition)
Some collection classes provide thread-safety of accesses to contained elements. If the {{helper}} field is contained in such a collection, the {{Helper}} object is guaranteed to be fully initialized before its reference is made visible. This compliant solution encases the {{helper}} field is initialized in a {{staticVector}} block. When initialized statically, any 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 Helper helper = new Helper(42);
public static Helper getHelper() {
return helper;
}
}
{code}
This requires .
{code:bgColor=#CCCCFF}
class Foo {
private Vector<Helper> helper;
public Helper getHelper() {
return helper.elementAt(0);
}
public void initialize() {
helper = new Vector<Helper>();
helper.add(new Helper(42));
}
}
{code}
If the {{Foo}} object were mutable, additional locking may be required to ensure that this ability does not lead to data races.
h2. Compliant Solution (static initialization)
In this compliant solution, the {{helper}} field is toinitialized bein declareda {{static}} block.
Note thatWhen ifinitialized thestatically, Helperany object is guaranteed mutableto be orfully not thread-safe, you must add additional locking to protect its fields from being modified concurrently by multiple threads as well. See [CON11-J. Do not assume that declaring an object volatile guarantees visibility of its members] for more information.
Also, if the {{Foo}} object allows you to change what the {{helper}} fields points to, you will want additional locking to ensure that this ability does not lead to data races.
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}}. It is recommended that the field be declared {{final}} as well to sufficiently document the class's immutability property.
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)]
|