During initialization of a shared object, the object must only be accessible only to the thread constructing it. However, the object can be published safely published (that is, made visible to other threads) once it its initialization is initializedcomplete. The Java Memory Model memory model (JMM) 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 publishedprograms must prevent publication of partially initialized objects.
This guideline rule prohibits publishing a reference to a partially initialized member object instance before initialization completes while CON14has concluded. It specifically applies to safety in multithreaded code. TSM01-J. Do not let the " this " reference escape during object construction prohibits the this
reference of the current object from escaping its constructor. OBJ11-J. Be wary of letting constructors throw exceptions describes the consequences of publishing partially initialized objects even in single-threaded programs.
Noncompliant Code Example
This noncompliant code example constructs a Helper
object in the initialize()
method of the Foo
class Foo
. The helper
field is initialized by Helper
object's fields are initialized by its constructor.
Code Block | ||
---|---|---|
| ||
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;
}
// ...
}
|
If a thread accesses were to access helper
using the getHelper()
method before the initialize()
has been called method executed, the thread will would observe an uninitialized helper
field. Later, if one thread calls initialize()
, and another calls getHelper()
, the second thread might could observe one of the following:
- The
helper
reference asnull
...
- A fully initialized
Helper
object with then
field set to 42
...
- A partially initialized
Helper
object with an uninitializedn
, which contains the default value0
...
In particular, the JMM permits compilers to allocate memory for the new Helper
object and to assign it a reference to that memory to the helper
field before initializing itthe new Helper
object. In other words, the compiler can reorder the write to the helper
instance field with and the write that initializes the Helper
object (that is, this.n = n
) such so that the former occurs first. This exposes can expose a race window during which other threads may can observe a partially - initialized Helper
object instance.
There is a separate issue in that, if two threads : if more than one thread were to call initialize()
, then two multiple Helper
objects are would be created. This is merely a performance issue and not a correctness issue because n
will issue—correctness would be preserved. The n
field of each object would be properly initialized and the unused Helper
objects will object (or objects) would eventually be garbage-collected.
Compliant Solution (Synchronization)
Publishing partially-constructed object reference can be prevented by using method synchronizationAppropriate use of method synchronization can prevent publication of references to partially initialized objects, as shown by in this compliant solution.:
Code Block | ||
---|---|---|
| ||
class Foo {
private Helper helper;
public synchronized Helper getHelper() {
return helper;
}
public synchronized void initialize() {
helper = new Helper(42);
}
}
|
Synchronizing both methods guarantees that they will not cannot execute concurrently. If one thread calls were to call initialize()
just before another thread calls called getHelper()
, the synchronized initialize()
method will would always finish first. The synchronized
keywords establish a happens-before relationship between the two threads. This guarantees that Consequently, the thread calling getHelper()
sees would see either the fully initialized Helper
object or none at all an absent Helper
object (that is, helper
contains would contain a null reference). This approach guarantees proper publication both for both immutable and mutable members.
Compliant Solution (Final Field)
If the helper
field is declared as final
, it is guaranteed to be fully constructed before its reference is made visibleThe JMM guarantees that the fully initialized values of fields that are declared final are safely published to every thread that reads those values at some point no earlier than the end of the object's constructor.
Code Block | ||
---|---|---|
| ||
class Foo { private final Helper helper; public Helper getHelper() { return helper; } public Foo() { // Point 1 helper = new Helper(42); // Point 2 } } |
However, this solution requires that the {{helper}} field is assigned to a new object during construction. According to the Java Language Specification, Section 17the assignment of a new Wiki Markup Helper
instance to helper
from Foo's constructor. According to The Java Language Specification, §17.5.2, "Reading Final Fields During Construction" \ [[JLS 05|AA. Java References#JLS 05]\]JLS 2015]:
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, otherwise it sees the default value.
Consequently, the reference to the helper
field should not be published before class Foo
instance should remain unpublished until the Foo
class's constructor has finished its initialization completed (see CON14TSM01-J. Do not let the " this " reference escape during object constructionfor additional information).
Compliant Solution (Final Field and Thread-
...
Safe Composition)
Some collection classes provide thread-safe access to contained elements. If the When a Helper
object is inserted into such a collection, it is guaranteed to be fully initialized before its reference is made visible. This compliant solution encapsulates the helper
field in a Vector<Helper>
.
Code Block | ||
---|---|---|
| ||
class Foo { private final Vector<Helper> helper; public 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)); } } } |
The helper
field is declared as final to guarantee that the vector is always created before any accesses take place. It can be initialized safely initialized by invoking the synchronized initialize()
method, which is synchronized and checks ensures that only one Helper
object is ever added to the vector. If getHelper()
is invoked before initialize()
, it calls initializethe getHelper()
to avoid avoids the possibility of a null-pointer dereference by the client. The getHelper()
method does not require synchronization to simply return Helper
, and because the conditionally invoking initialize()
. Although the isEmpty()
call in getHelper()
is made from an unsynchronized context (which permits multiple threads to decide that they must invoke initialize
) race conditions that could result in addition of a second object to the vector are nevertheless impossible. The synchronized initialize()
method also checks to make sure whether helper
is empty before adding a new Helper
object, there is no possibility of exploiting a race condition to add a second object to the vector, and at most one thread can execute initialize()
at any time. Consequently, only the first thread to execute initialize()
can ever see an empty vector and the getHelper()
method can safely omit any synchronization of its own.
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 ensuring that the object referenced by the field is fully initialized before its reference is made becomes visible. :
Code Block | ||
---|---|---|
| ||
// Immutable Foo final class Foo { private static final Helper helper = new Helper(42); public static Helper getHelper() { return helper; } } |
This requires the The helper
field to should be declared static
. Although not a requirement, it is recommended that the field be declared final to document the class's immutability.
According to JSR-133, Section 9.2.3, "Static Final Fields" \ [[JSR-133 04|AA. Java References#JSR-133 04]\]2004]: Wiki Markup
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.
Compliant Solution (Immutable
...
Object - Final
...
Fields, Volatile Reference)
...
The Java memory model guarantees that any final fields of an object are fully initialized before a published object becomes visible \[[Goetz 06|AA. Java References#Goetz 06]\]. By declaring {{n}} as final, the {{Helper}} class is made [immutable|BB. Definitions#immutable]. Furthermore, if the {{helper}} field is declared {{volatile}} in compliance with [CON02-J. Ensure visibility of shared references to immutable objects], {{Helper}}'s reference is guaranteed to be made visible to any thread that calls {{getHelper()}} after {{Helper}} has been fully JMM guarantees that any final fields of an object are fully initialized before a published object becomes visible [Goetz 2006a]. By declaring n
final, the Helper
class is made immutable. Furthermore, if the helper
field is declared volatile in compliance with VNA01-J. Ensure visibility of shared references to immutable objects, Helper
's reference is guaranteed to be made visible to any thread that calls getHelper()
only after Helper
has been fully initialized.
Code Block | ||
---|---|---|
| ||
class Foo {
private volatile Helper helper;
public Helper getHelper() {
return helper;
}
public void initialize() {
helper = new Helper(42);
}
}
// Immutable Helper
public final class Helper {
private final int n;
public Helper(int n) {
this.n = n;
}
// ...
}
|
This compliant solution requires that helper
be declared as volatile and that class Helper
be is immutable. If it were not immutable, the code would violate CON11-J. Do not assume that declaring an object reference volatile guarantees visibility of its members and additional synchronization would be necessary (see the next compliant solution). And if the helper
field were not volatile, it would violate CON02 VNA01-J. Ensure visibility of shared references to immutable objects.
Similarly, Providing a public static factory method that returns a new instance of Helper
can be provided in class Helper
is both permitted and encouraged. This approach allows the Helper
instance to be created in a private constructor.
Compliant Solution (Mutable Thread-
...
Safe Object, Volatile Reference)
If When Helper
is mutable , but thread-safe, it can be published safely published by declaring the helper
field in the Foo
class Foo
as volatile. :
Code Block | ||
---|---|---|
| ||
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; private final Object lock = new Object(); public Helper(int n) { this.n = n; } public void setN(int value) { synchronized (lock) { n = value; } } } |
Because the Helper
object can change state after its construction, synchronization is necessary Synchronization is required to ensure the visibility of mutable members after initial publication . Consequently, because the Helper
object can change state after its construction. This compliant solution synchronizes the setN()
method is synchronized to provide guarantee the visibility of n
in this compliant solution (see CON11-J. Do not assume that declaring an object reference volatile guarantees visibility of its members).the n
field.
If the Helper
class is not properly were synchronized incorrectly, declaring helper
as volatile in the Foo
class Foo
would guarantee only guarantees the visibility of the initial publication of Helper
and not ; the visibility guarantee would exclude visibility of subsequent state changes. Consequently, volatile references alone are inadequate for publishing objects that are not thread-safe.
If the helper
field in the Foo
class Foo
is not declared as volatile, the n
field n
should must be declared as volatile so that to establish a happens-before relationship is established between the initialization of n
and the write of Helper
to the helper
field helper
. This is in compliance with CON11-J. Do not assume that declaring an object reference volatile guarantees visibility of its members. This is only required required only when the caller (class Foo
) cannot be trusted to declare helper
as volatile.
Because the the Helper
class is declared as public, it uses a private lock to handle synchronization in conformance with CON04 LCK00-J. Use private final lock objects to synchronize classes that may interact with untrusted code.
Exceptions
CON26TSM03-J-EX1EX0: Classes that prevent partially initialized objects from being used may publish partially initialized objects. This may could be implemented, for example, by setting a volatile boolean
Boolean flag in the last statement of the initializing code and then ensuring this flag was checking whether the flag is set before allowing the execution of any class methods to execute.
The following compliant solution illustrates shows this technique:
Code Block | ||
---|---|---|
| ||
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"); } // ... } // ... } |
This technique ensures that even if the a reference to the Helper
object instance is were published before its initialization is overwas complete, the instance is unusable. The instance is unusable because every would be unusable because each method within Helper
must check checks the flag to determine whether the initialization has finished.
Risk Assessment
Failing Failure to synchronize access to shared mutable data can cause different threads to observe different states of the object or to observe a partially initialized object.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|
TSM03-J |
Medium |
Probable |
Medium | P8 | L2 |
Automated Detection
...
Tool |
---|
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
...
Version | Checker | Description |
---|
Bibliography
[API 2006] | |
Item 48, "Synchronize Access to Shared Mutable Data" | |
Section 3.5.3 |
...
, "Safe |
...
Publication |
...
Idioms" |
...
[ |
...
Pattern #2, "One-Time Safe Publication" | |
[JPL 2006] | Section 14.10.2 |
...
, "Final |
...
Fields |
...
and |
...
Security" |
...
...
[Pugh 04|AA. Java References#Pugh 04]\]CON25-J. Ensure atomicity when reading and writing 64-bit values 11. Concurrency (CON) CON27-J. Ensure ThreadLocal variables are reinitialized when using thread pools