Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

During

...

initialization of a shared object,

...

the

...

object must be accessible only to the thread constructing it. However, the object can be published safely (that is, made visible to other threads) once its initialization is complete. The Java memory model (JMM) allows multiple threads to observe the object after its initialization has begun but before it has concluded. Consequently, programs must prevent publication of partially initialized objects.

This rule prohibits publishing a reference to a partially initialized member object instance before initialization has 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. The Helper object's fields are initialized by its constructor.

Code Block
bgColor#FFCCCC
 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 constructed object is not published.

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. All 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, still containing 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. 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 issue, not a correctness issue.


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

If a thread were to access helper using the getHelper() method before the initialize() method executed, the thread would observe an uninitialized helper field. Later, if one thread calls initialize() and another calls getHelper(), the second thread could observe one of the following:

  • The helper reference as null
  • A fully initialized Helper object with the n field set to 42
  • A partially initialized Helper object with an uninitialized n, which contains the default value 0

In particular, the JMM permits compilers to allocate memory for the new Helper object and to assign a reference to that memory to the helper field before initializing the new Helper object. In other words, the compiler can reorder the write to the helper instance field and the write that initializes the Helper object (that is, this.n = n) so that the former occurs first. This can expose a race window during which other threads can observe a partially initialized Helper object instance.

There is a separate issue: if more than one thread were to call initialize(), multiple Helper objects would be created. This is merely a performance issue—correctness would be preserved. The n field of each object would be properly initialized and the unused Helper object (or objects) would eventually be garbage-collected.

Compliant Solution (Synchronization)

Appropriate use of method synchronization can prevent publication of references to partially initialized objects, as shown in this compliant solution:

Code Block
bgColor#CCCCFF
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 cannot execute concurrently. If one thread were to call initialize() just before another thread called getHelper(), the synchronized initialize() method would always finish first. The synchronized keywords establish a happens-before relationship between the two threads. Consequently, the thread calling getHelper() would see either the fully initialized Helper object or an absent Helper object (that is, helper would contain a null reference). This approach guarantees proper publication both for immutable and mutable members.

Compliant Solution (Final Field)

The 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
bgColor#CCCCFF
class Foo {
  private final Helper helper;

  public Helper getHelper() {
    return helper;
  }

  public synchronized void initializeFoo() {
    // Point 1
    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, the two synrchonizations establish a [happens-before relation|BB. Definitione#happens-before order] between the two threads. This guarantees that the thread calling {{getHelper()}} sees the full state of the thread that called {{initialize()}}, including a fully-constructed {{Helper}} object.  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  // Point 2
  }
}

However, this solution requires the assignment of a new Helper instance to helper from Foo's constructor. According to The Java Language Specification, §17.5.2, "Reading Final Fields During Construction" [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, it sees the default value.

Consequently, the reference to the helper instance should remain unpublished until the Foo class's constructor has completed (see TSM01-J. Do not let the this reference escape during object construction for additional information).

Compliant Solution (Final Field and Thread-Safe Composition)

Some collection classes provide thread-safe access to contained elements. 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
bgColor#CCCCFF
visible.

{code:bgColor=#CCCCFF}
class Foo {
  private final HelperVector<Helper> helper;

  public Helper getHelperFoo() {
    return helperhelper = new Vector<Helper>();
  }

  public Helper FoogetHelper() {
    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 final to guarantee that the vector is always created before any accesses take place. It can be initialized safely by invoking the synchronized initialize() method, which ensures that only one Helper object is ever added to the vector. If invoked before initialize(), the getHelper() avoids the possibility of a null-pointer dereference by 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 whether helper is empty before adding a new Helper object, 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 statically, ensuring that the object referenced by the field is fully initialized before its reference becomes visible:

Code Block
bgColor#CCCCFF
// Immutable Foo
final class Foo {
  private static final Helper helper = new Helper(42);

  public static Helper getHelper() {
    return helper;
  }
}

The helper field should be declared final to document the class's immutability.

According to JSR-133, Section 9.2.3, "Static Final Fields" [JSR-133 2004]:

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 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
bgColor#CCCCFF
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 volatile and that class Helper is immutable. If the helper field were not volatile, it would violate VNA01-J. Ensure visibility of shared references to immutable objects.

Providing a public static factory method that returns a new instance of 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)

When Helper is mutable but thread-safe, it can be published safely by declaring the helper field in the Foo class volatile:

Code Block
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;
  private final Object lock = new Object();

  public Helper(int n) {
    this.n = n;

  }

  public void setN(int value) {
    synchronized (lockhelper = 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 in a {{Vector}}. It synchronizes the initialization to prevent two {{Helper}} objects from being created and added to the vector.

{code:bgColor=#CCCCFF}
class Foo {
  private Vector<Helper> helper;

  public Helper getHelper() {
    return helper.elementAt(0);
  }

  public synchronized void initialize() {
    if (helper == null) {
      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.

This code also adds synchronizes {{initialize()}} and adds a check in order to prevent {{helper}} from getting initialized twice. Whereas a simple {{Helper}} object getting initialized twice with the same value is merely a performace issue, the consequences of this initialization may be more severe, including the creation of a vector with two {{Helper}} objects.


h2. Compliant Solution ({{final}} + thread-safe composition)

This solution is similar to the previous one, except that the {{helper}} field is declared {{final}}. This forces us to create it in the constructor, but we can still create the {{Helper}} object in the {{initialize()}} method.

{code:bgColor=#CCCCFF}
class Foo {
  private final Vector<Helper> helper;

  public Helper getHelper() {
    return helper.elementAt(0);
  }

  Foo() {
    helper = new Vector<Helper>();  
  }
  public synchronized void initialize() {
    if (helper.isEmpty()) {
      helper.add(new Helper(42))n = value;
    }
  }
}
{code}


h2. Compliant Solution (static initialization)

In this compliant solution, the {{helper}} field is initialized in a {{static}} 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 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.

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, {{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 {{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(42);
  }
}

// Immutable Helper
public class Helper {
  private final int n;

  public Helper(int n) {
    this.n = n;
  }
  // ...
}
{code}

Note that if the state of the {{Helper}} object could be changed after its construction, additional locking would be necessary to ensure all threads see the most recent state. 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, but thread-safe member object is expected to continually publish its most recent state when its reference is declared {{volatile}}. The use of {{volatile}} guarantees the visibility of only the initial publication and not of subsequent state changes. Consequently, the use of {{volatile}} to publish thread-safe objects is often not very useful, whereas immutable objects can safely use this solution.

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>}}.

This code requires both that {{helper}} be {{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 if it were not {{volatile}}, it would violate [CON09-J. Do not assume that classes having only immutable members are thread-safe]. See this rule for more information on how to safely publish immutable objects.


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]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!|09. Input Output (FIO)]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!|09. Input Output (FIO)]

Synchronization is required to ensure the visibility of mutable members after initial publication because the Helper object can change state after its construction. This compliant solution synchronizes the setN() method to guarantee the visibility of the n field.

If the Helper class were synchronized incorrectly, declaring helper volatile in the Foo class would guarantee only the visibility of the initial publication of Helper; 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 is not declared volatile, the n field must be declared volatile to establish a happens-before relationship between the initialization of n and the write of Helper to the helper field. This is required only when the caller (class Foo) cannot be trusted to declare helper volatile.

Because the Helper class is declared public, it uses a private lock to handle synchronization in conformance with LCK00-J. Use private final lock objects to synchronize classes that may interact with untrusted code.

Exceptions

TSM03-J-EX0: Classes that prevent partially initialized objects from being used may publish partially initialized objects. This could be implemented, for example, by setting a volatile Boolean flag in the last statement of the initializing code and checking whether the flag is set before allowing class methods to execute.

The following compliant solution shows this technique:

Code Block
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");
    }
    // ...
  }
  // ...
}

This technique ensures that if a reference to the Helper object instance were published before its initialization was complete, the instance would be unusable because each method within Helper checks the flag to determine whether the initialization has finished.

Risk Assessment

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

ToolVersionCheckerDescription

Bibliography

[API 2006]


[Bloch 2001]

Item 48, "Synchronize Access to Shared Mutable Data"

[Goetz 2006a]

Section 3.5.3, "Safe Publication Idioms"

[Goetz 2007]

Pattern #2, "One-Time Safe Publication"

[JPL 2006]

Section 14.10.2, "Final Fields and Security"

[Pugh 2004]



...

Image Added Image Added Image Added