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. The related rule Rule TSM01-J. Do not let the this reference escape during object construction prohibits the this reference of the current object from escaping its constructor. Also see Rule OBJ11-J. Be wary of letting constructors throw exceptions for describes some consequences of publishing partially - initialized objects even in single-threaded programs.

...

If a thread were to access helper using the getHelper() method before the initialize() method has 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 The helper reference as null
  • a A fully - initialized Helper object with the n field set to 42
  • a 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 only 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) will would eventually be garbage-collected.

...

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

...

Compliant Solution (Final Field)

The Java Memory Model 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 later than the end of the object's constructor.

...

Consequently, the reference to the helper instance should remain unpublished until the Foo class's constructor has completed. See rule 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. 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 encapsulates the helper field in a Vector<Helper>.

...

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 is invoked before initialize(), The the getHelper() avoids the possibility of a null-pointer de-reference 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. Consequently, the getHelper() method can safely omit any synchronization of its own.

...

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. As a resultThus, no special rules in the JMM are needed for static final fields.

Compliant Solution (Immutable Object - Final Fields, Volatile Reference)

...

This compliant solution requires that helper be declared volatile and that class Helper be is immutable. If the helper field were non-not volatile, it would violate rule 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.

...

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. See rule VNA06-J. Do not assume that declaring a reference volatile guarantees visibility of the members of the referenced object for additional information.

If the Helper class was 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.

...

TSM03-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 Boolean flag in the last statement of the initializing code and checking whether this flag is set before allowing class methods to execute.

...

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 
          "Cannot use partially initialized instance");
    }
    // ...
  }
  // ...
}

This technique ensures that , in the event 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.

...

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

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="483c8581053df7b9-466604d6-45cb429f-a8e8aeff-f0a0cbe245ccc7c8eaea7c2e"><ac:plain-text-body><![CDATA[

[[API 2006

AA. Bibliography#API 06]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="d5f1bbb9052ff72f-958656b6-4bce4bf5-988d9125-833809cf1464d527c6f208a4"><ac:plain-text-body><![CDATA[

[[Bloch 2001

AA. Bibliography#Bloch 01]]

Item 48: ". Synchronize access to shared mutable data "

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="e9a0eeb804ba762f-60cf2eb6-444a40ba-b9e89124-ee96b87ebd41972adff65525"><ac:plain-text-body><![CDATA[

[[Goetz 2006

AA. Bibliography#Goetz 06]]

Section 3.5.3 ", Safe Publication Idioms "

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="26976fb7c93ad314-0cb5f90b-4f2649b0-b9598ea8-6e2e3b46a82ebbd63e110afa"><ac:plain-text-body><![CDATA[

[[Goetz 2007

AA. Bibliography#Goetz 07]]

Pattern #2: "one-time safe publication" , One-Time Safe Publication

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="788984e5b4125b27-5d1cca2c-49ff4873-bb9bae98-86b7c6937b2fc0a4e73d2059"><ac:plain-text-body><![CDATA[

[[JPL 2006

AA. Bibliography#JPL 06]]

14.10.2. ", Final Fields and Security "

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="9343c44885ae738e-6504f77a-405448e7-960186e0-b35f2596c709aec57d5bee7d"><ac:plain-text-body><![CDATA[

[[Pugh 2004

AA. Bibliography#Pugh 04]]

 

]]></ac:plain-text-body></ac:structured-macro>

...